feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

+6 -1
View File
@@ -45,7 +45,12 @@ export const hydrateShippingOrderExtractionState = (message: ChatMessage): ChatM
if (!state || typeof state !== 'object') return message;
const status = String((state as Record<string, unknown>).status || '');
if (!['queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'].includes(status)) return message;
message.shipping_order_extraction_state = state as ShippingOrderExtractionState;
const normalized = state as ShippingOrderExtractionState;
if (normalized.supersedingRunNo) {
normalized.isCurrent = false;
normalized.readOnlyReason = normalized.readOnlyReason || 'superseded_by_newer_run';
}
message.shipping_order_extraction_state = normalized;
return message;
};
+218 -213
View File
@@ -1,38 +1,48 @@
/**
* features/chat/api/shipping.api.ts
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、人工决策、订单抽取取消/时间线与 Excel 导出。
* 用途:封装发货通知相关 HTTP API,包括任务查询、人工决策、订单抽取取消/时间线与 Excel 导出。
* 依赖:统一 requestJson / BusinessError、shipping.api.types 类型定义。
* 逻辑:上游由 useChatShipping、shipping-task-center 与 shipping/* handler 调用;
* 含阶段 4+ `/shipping-processing/*` 统一进度投影;
* co8 后已移除 create_batch / Workflow list·cancel·reparse 客户端导出;
* 「我的待办」列表/徽标见 features/workspace/api/shipping-tasks.api.ts。
*/
import { BusinessError, requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
import {
normalizeShippingProcessingProjection,
normalizeShippingProcessingWorkItems,
} from '../shipping/normalizeShippingProcessing';
import type {
ShippingBatchSummary,
ShippingBatchUiState,
ShippingConversationWorkspace,
ShippingDecisionResponse,
ShippingOrderExtractionDocumentsResponse,
ShippingNoticeHeader,
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingNoticeIntakeResponse,
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskBatchDispositionResponse,
ShippingTaskPage,
ShippingTaskSummary,
ShippingCustomerOption,
ShippingOrderExtractionDocumentResult,
ShippingOrderExtractionRun,
ShippingOrderExtractionProgressEvent,
ShippingOrderExtractionRunCreateResponse,
OrderExtractionSubmissionRequest,
OrderExtractionSubmissionResponse,
ConversationProcessingProjection,
ShippingOrderReviewAuditTimelinePage,
ShippingTaskAuditTimelinePage,
ShippingOrderReviewCase,
ShippingOrderReviewCustomerResolution,
ShippingOrderReviewDuplicate,
ShippingOrderReviewFieldConflict,
ShippingOrderReviewLineFulfillment,
ShippingOrderReviewLineFulfillmentDecisionCode,
ShippingOrderReviewReservation,
ShippingOrderReviewResumeOutcome,
ShippingDuplicateAction,
ShippingOrderReviewDraftWrite,
ShippingOrderReviewEvidence,
@@ -45,9 +55,6 @@ import type {
ShippingOrderReviewLlmSuggestionResponse,
ShippingOrderReviewReparseResponse,
ShippingOrderReviewRun,
ShippingWorkflow,
ShippingWorkflowConversationProjection,
ShippingWorkflowItem,
ShippingTaskUiState,
} from '../types/shipping.api.types';
@@ -112,45 +119,29 @@ export const listWorkspaceShippingTasks = (params?: {
return requestJson<ShippingTaskPage>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
};
export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
/** 拉取当前用户的发货批次摘要列表。 */
const sp = new URLSearchParams();
if (params?.limit) sp.set('limit', String(params.limit));
const qs = sp.toString();
return requestJson<ShippingBatchSummary[]>(`/api/workspace/shipping-batches${qs ? '?' + qs : ''}`);
};
/** 拉取用户可见 Agent 列表,供发货工作台跳转 Chat 时定位目标 Agent。 */
export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[]>('/api/agents');
/** 获取批次详情、批次任务列表与当前焦点任务。 */
export const getWorkspaceShippingBatch = (batchNo: string) =>
requestJson<ShippingBatchUiState>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
);
/** 获取批次级 UI State,供工作台、步骤条和任务卡片统一消费。 */
export const getWorkspaceShippingBatchUiState = (batchNo: string) =>
requestJson<ShippingBatchUiState>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/ui-state`,
);
/** 获取一个 Agent 会话下的多批次执行工作台快照。 */
export const getWorkspaceShippingConversationBatches = (conversationId: string) =>
requestJson<ShippingConversationWorkspace>(
`/api/workspace/shipping-conversations/${encodeURIComponent(conversationId)}/batch-workspace`,
);
/** 获取指定批次当前焦点任务。 */
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
requestJson<ShippingTaskSummary>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
);
/** 获取单个发货任务详情。 */
export const getWorkspaceShippingTask = (taskNo: string) =>
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
/**
* 分页拉取任务工作台统一审计时间线(ShippingAuditEvent 单源)。
*/
export const listWorkspaceShippingTaskAuditTimeline = (
taskNo: string,
params?: { page?: number; page_size?: number },
) => {
const sp = new URLSearchParams();
if (params?.page) sp.set('page', String(params.page));
if (params?.page_size) sp.set('page_size', String(params.page_size));
const qs = sp.toString();
return requestJson<ShippingTaskAuditTimelinePage>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/audit-timeline${qs ? `?${qs}` : ''}`,
);
};
/** 获取单票任务 UI State,后续 Chat 按钮与顶部步骤条统一读取此状态。 */
export const getWorkspaceShippingTaskUiState = (taskNo: string) =>
requestJson<ShippingTaskUiState>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/ui-state`);
@@ -188,6 +179,86 @@ export const createWorkspaceShippingOrderExtractionRun = (payload: {
jsonPost(payload),
);
/**
* 统一订单抽取提交:后端事务内裁决追加或新建用户可见任务。
* 核心逻辑:携带 submission_id 幂等;前端不得本地选择 append/create API。
*/
export const createWorkspaceOrderExtractionSubmission = (
payload: OrderExtractionSubmissionRequest,
) => requestJson<OrderExtractionSubmissionResponse>(
'/api/workspace/shipping-notice/order-extraction-submissions',
jsonPost(payload),
);
/**
* 拉取统一 ShippingProcessingProjection(唯一进度读源;含 order_intake / order_task)。
* 核心逻辑:内嵌 conversation_processing 可选;缺省时前端由 work_items 合成分组;
* 旧 conversation processing GET 已移除(无历史兼容)。
*/
export const getWorkspaceShippingProcessing = async (
conversationId: string,
signal?: AbortSignal,
) => {
const raw = await requestJson<{
conversation_id?: string;
work_items?: unknown[];
conversation_processing?: ConversationProcessingProjection | null;
}>(
`/api/workspace/shipping-processing/conversations/${encodeURIComponent(conversationId)}`,
{ signal },
);
return {
conversation_id: String(raw?.conversation_id || conversationId),
work_items: normalizeShippingProcessingWorkItems(raw?.work_items),
conversation_processing: raw?.conversation_processing ?? null,
};
};
/**
* 按工作项类型与编号读取统一进度投影详情。
*/
export const getWorkspaceShippingProcessingWorkItem = async (
workItemType: 'order_intake' | 'order_task',
workItemNo: string,
signal?: AbortSignal,
) => {
const raw = await requestJson<Record<string, unknown>>(
`/api/workspace/shipping-processing/work-items/${encodeURIComponent(workItemType)}/${encodeURIComponent(workItemNo)}`,
{ signal },
);
const normalized = normalizeShippingProcessingProjection(raw);
if (!normalized) {
throw new BusinessError({
message: 'Invalid shipping processing projection',
code: 'SHIPPING.PROCESSING_PROJECTION_INVALID',
status: 500,
});
}
return normalized;
};
/**
* 标记会话用户可见任务为当前焦点(写审计;返回最新 processing)。
*/
export const focusWorkspaceConversationTask = (
taskNo: string,
payload?: { conversation_id?: string | null },
) => requestJson<{ processing: ConversationProcessingProjection }>(
`/api/workspace/shipping-notice/conversation-tasks/${encodeURIComponent(taskNo)}/focus`,
jsonPost(payload || {}),
);
/**
* 标记用户可见任务详情已查看(viewed,不等于业务已处理)。
*/
export const markWorkspaceConversationTaskViewed = (
taskNo: string,
payload?: { conversation_id?: string | null },
) => requestJson<{ processing: ConversationProcessingProjection }>(
`/api/workspace/shipping-notice/conversation-tasks/${encodeURIComponent(taskNo)}/viewed`,
jsonPost(payload || {}),
);
/**
* 查询单个订单抽取 Run,供聊天页短轮询。
* @param runNo - Run 业务编号。
@@ -370,6 +441,7 @@ export const retryWorkspaceShippingOrderReviewCustomerResolution = (caseNo: stri
requestJson<{
case: ShippingOrderReviewCase;
customer_resolution: ShippingOrderReviewCustomerResolution;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/retry`,
{ method: 'POST' },
@@ -384,6 +456,7 @@ export const confirmWorkspaceShippingOrderReviewCustomer = (
) => requestJson<{
case: ShippingOrderReviewCase;
customer_resolution: ShippingOrderReviewCustomerResolution;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer-resolution/confirm`,
{
@@ -400,6 +473,7 @@ export const refreshWorkspaceShippingOrderReviewDuplicate = (caseNo: string) =>
requestJson<{
case: ShippingOrderReviewCase;
duplicate: ShippingOrderReviewDuplicate;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-refresh`,
{ method: 'POST' },
@@ -418,6 +492,7 @@ export const resolveWorkspaceShippingOrderReviewDuplicate = (
) => requestJson<{
case: ShippingOrderReviewCase;
duplicate: ShippingOrderReviewDuplicate;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/duplicate-resolution`,
{
@@ -457,6 +532,7 @@ export const resolveWorkspaceShippingOrderReviewFieldConflict = (
) => requestJson<{
case: ShippingOrderReviewCase;
field_conflicts: ShippingOrderReviewFieldConflict[];
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/field-conflicts/${encodeURIComponent(conflictKey)}/resolve`,
{
@@ -606,6 +682,107 @@ export const adjudicateWorkspaceShippingOrderReviewLlmSuggestion = (
jsonPost(body),
);
/**
* 显式重校验 Reservation 并触发统一恢复协调。
* 核心逻辑:validate_draft + resume;返回 case 与 resume_outcome。
*/
export const revalidateWorkspaceShippingOrderReviewReservation = (
caseNo: string,
payload: { expected_draft_version: number },
) => requestJson<{
case: ShippingOrderReviewCase;
reservation?: ShippingOrderReviewReservation;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reservation/revalidate`,
jsonPost(payload),
);
/**
* 分页拉取复核 Case 业务审计时间线(打开抽屉时按需加载)。
*/
export const listWorkspaceShippingOrderReviewAuditTimeline = (
caseNo: string,
params?: { page?: number; page_size?: number },
) => {
const sp = new URLSearchParams();
if (params?.page) sp.set('page', String(params.page));
if (params?.page_size) sp.set('page_size', String(params.page_size));
const qs = sp.toString();
return requestJson<ShippingOrderReviewAuditTimelinePage>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/audit-timeline${qs ? `?${qs}` : ''}`,
);
};
/**
* 写入一行履约决定(等待补货 / 完整行先行 / 关闭等)。
*/
export const decideWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
line_key: string;
decision_code: ShippingOrderReviewLineFulfillmentDecisionCode | string;
reason?: string;
expected_draft_version?: number;
},
) => requestJson<{
case: ShippingOrderReviewCase;
decision?: Record<string, unknown>;
line_fulfillment?: ShippingOrderReviewLineFulfillment;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/decide`,
jsonPost(payload),
);
/**
* 为选中完整明细行创建履约波次 Task。
*/
export const waveWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
line_keys: string[];
expected_draft_version: number;
idempotency_key: string;
reason?: string;
},
) => requestJson<{
case: ShippingOrderReviewCase;
line_fulfillment?: ShippingOrderReviewLineFulfillment;
resume_outcome?: ShippingOrderReviewResumeOutcome;
task_no?: string | null;
wave_no?: number | null;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/wave`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Idempotency-Key': payload.idempotency_key,
},
body: JSON.stringify(payload),
},
);
/**
* 关闭指定行或 Case 剩余开放行。
*/
export const closeWorkspaceShippingOrderReviewLineFulfillment = (
caseNo: string,
payload: {
reason: string;
line_keys?: string[];
expected_draft_version?: number;
},
) => requestJson<{
case: ShippingOrderReviewCase;
line_fulfillment?: ShippingOrderReviewLineFulfillment;
resume_outcome?: ShippingOrderReviewResumeOutcome;
}>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/line-fulfillment/close`,
jsonPost(payload),
);
/** 打开版本历史抽屉时写入服务端访问审计(失败不阻断 UI)。 */
export const auditWorkspaceShippingOrderReviewVersionHistory = (caseNo: string) =>
requestJson<{ audited: boolean; case_no: string }>(
@@ -645,92 +822,6 @@ export const markWorkspaceShippingOrderExtractionRunSeen = (runNo: string) =>
jsonPost(),
);
/**
* 列出会话开放 Workflow 与 Items(版面阶段 Item 已存在)。
* @param conversationId - 聊天会话 ID
* @param options.signal - 可选中止信号(轮询超时)
*/
export const listWorkspaceShippingWorkflows = (
conversationId: string,
options?: { signal?: AbortSignal },
) => {
const params = new URLSearchParams({ conversation_id: conversationId });
return requestJson<ShippingWorkflowConversationProjection>(
`/api/workspace/shipping-notice/workflows?${params.toString()}`,
{ signal: options?.signal },
);
};
/**
* 读取单个 Workflow 详情(含 Items 摘要)。
* @param workflowNo - Workflow 业务编号
*/
export const getWorkspaceShippingWorkflow = (
workflowNo: string,
options?: { signal?: AbortSignal },
) =>
requestJson<ShippingWorkflow>(
`/api/workspace/shipping-notice/workflows/${encodeURIComponent(workflowNo)}`,
{ signal: options?.signal },
);
/**
* 读取单个 WorkflowItem 详情(默认含 events)。
* @param itemNo - Item 业务编号
* @param options.include_events - 是否附带事件时间线;默认 true
* @param options.signal - 可选中止信号
*/
export const getWorkspaceShippingWorkflowItem = (
itemNo: string,
options?: { signal?: AbortSignal; include_events?: boolean },
) => {
const params = new URLSearchParams();
if (options?.include_events === false) {
params.set('include_events', 'false');
} else if (options?.include_events === true) {
params.set('include_events', 'true');
}
const query = params.toString();
return requestJson<ShippingWorkflowItem>(
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}${query ? `?${query}` : ''}`,
{ signal: options?.signal },
);
};
/**
* 取消单个 WorkflowItem;须填写 reason,可选乐观锁。
* @param itemNo - Item 业务编号
* @param payload.reason - 取消原因(必填)
* @param payload.expected_lock_version - 可选乐观锁版本
*/
export const cancelWorkspaceShippingWorkflowItem = (
itemNo: string,
payload: { reason: string; expected_lock_version?: number | null },
) =>
requestJson<{ item: ShippingWorkflowItem }>(
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/cancel`,
jsonPost(payload),
);
/**
* 对单个 WorkflowItem 发起重试/重新识别。
* 核心逻辑:POST reparse;后端可能并行补齐,客户端契约先行对齐。
* @param itemNo - Item 业务编号
* @param payload.reason - 重识别原因(必填)
* @param payload.comment - 可选补充说明
*/
export const reparseWorkspaceShippingWorkflowItem = (
itemNo: string,
payload: { reason: string; comment?: string | null },
) =>
requestJson<{ item: ShippingWorkflowItem; reused?: boolean }>(
`/api/workspace/shipping-notice/workflow-items/${encodeURIComponent(itemNo)}/reparse`,
jsonPost({
reason: payload.reason,
comment: payload.comment ?? undefined,
}),
);
/** 按会话恢复订单抽取 Run,刷新页面后不依赖聊天 SSE 历史。 */
export const listWorkspaceShippingOrderExtractionRuns = (
conversationId?: string | null,
@@ -865,56 +956,6 @@ export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: F
return assertShippingOk(body);
}
/**
* 批量上传多份发货通知并创建批次。
* @param files - 发货通知附件列表
* @param conversationId - 可选会话 ID
* @returns 批次与任务创建结果
*/
export async function createWorkspaceShippingBatchFromNotices(
files: File[],
conversationId?: string,
idempotencyKey?: string,
) {
const form = new FormData();
files.forEach((file) => form.append('files', file));
if (conversationId) form.append('conversation_id', conversationId);
if (idempotencyKey) form.append('idempotency_key', idempotencyKey);
const headers: Record<string, string> = {};
if (idempotencyKey) {
headers['Idempotency-Key'] = idempotencyKey;
}
const body = await requestJson<ShippingNoticeUploadResponse & ShippingApiStatusPayload & {
error?: string;
batch_no?: string;
idempotent_replay?: boolean;
file_summary?: unknown;
data?: unknown;
}>('/api/workspace/shipping-batches/create-from-notices', {
method: 'POST',
body: form,
headers,
});
return assertShippingOk(body);
}
/**
* 切换批次当前焦点任务。
* @param batchNo - 批次编号
* @param taskNo - 目标任务编号
* @returns 更新后的批次摘要与焦点任务
*/
export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, taskNo: string) {
const body = await requestJson<ShippingApiStatusPayload & {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary;
}>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
jsonPost({ task_no: taskNo }),
);
return assertShippingOk(body);
}
/**
* 重试当前发货任务。
* @param taskNo - 发货任务编号
@@ -929,19 +970,6 @@ export async function retryWorkspaceShippingTask(taskNo: string, comment?: strin
return assertShippingOk(body);
}
/**
* 重试批次中仍可自动推进的任务。
* @param batchNo - 批次编号
* @returns 批次重试结果
*/
export async function retryWorkspaceShippingBatchPending(batchNo: string) {
const body = await requestJson<ShippingApiStatusPayload>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/retry-pending`,
jsonPost(),
);
return assertShippingOk(body);
}
/**
* 提交人工决策。
* @param taskNo - 发货任务编号
@@ -1349,29 +1377,7 @@ export const resolveShippingNoticeCandidateDuplicate = (
},
);
export const createWorkspaceShippingBatchFromIntakes = (
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
) =>
requestJson<ShippingCreateBatchFromIntakesResponse>('/api/workspace/shipping-batches/create-from-intakes', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
},
body: JSON.stringify({
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
}),
});
export type {
ShippingBatchSummary,
ShippingBatchUiState,
ShippingChatAction,
ShippingConversationBatch,
ShippingConversationWorkspace,
@@ -1383,7 +1389,6 @@ export type {
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingNoticeIntakeResponse,
ShippingCreateBatchFromIntakesResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskBatchDispositionResponse,
@@ -77,6 +77,35 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
);
/** 同一 Run 只展示最后一张状态卡,避免历史恢复/SSE 补帧造成重复窗口。 */
const isDuplicateShippingExtractionMessage = (items: ChatMessage[], index: number): boolean => {
const current = items[index];
if (!current?.shipping_order_extraction_state) return false;
const payload = current.payload && typeof current.payload === 'object'
? current.payload as Record<string, unknown>
: {};
const identity = String(
payload.order_extraction_run_no
|| payload.formId
|| current.shipping_order_extraction_state.runNo
|| '',
).trim();
if (!identity) return false;
return items.slice(index + 1).some((candidate) => {
if (!candidate?.shipping_order_extraction_state) return false;
const candidatePayload = candidate.payload && typeof candidate.payload === 'object'
? candidate.payload as Record<string, unknown>
: {};
const candidateIdentity = String(
candidatePayload.order_extraction_run_no
|| candidatePayload.formId
|| candidate.shipping_order_extraction_state.runNo
|| '',
).trim();
return candidateIdentity === identity;
});
};
/**
* 标记“当前消息后面是否还存在新的 assistant 消息”。
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
@@ -111,7 +140,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
<template v-for="(msg, index) in messages" :key="getMessageKey(msg, index)">
<ChatMessageBubble
v-if="shouldRenderMessage(msg)"
v-if="shouldRenderMessage(msg) && !isDuplicateShippingExtractionMessage(messages, index)"
:message="msg"
:index="index"
:message-count="messages.length"
@@ -84,11 +84,11 @@ type MaintenanceRecordPanelCommand = {
const page = useChatPageContext();
const shippingWorkflow = useShippingNoticeWorkflow({
const shippingProcessing = useShippingNoticeWorkflow({
conversationId: () => page.conversationId,
refreshTrigger: () => page.workflowRefreshTrigger,
});
provide(SHIPPING_WORKFLOW_KEY, shippingWorkflow);
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
const route = useRoute();
@@ -155,12 +155,7 @@ const activeExtractionRunNo = computed(() => {
const showShippingWorkflowTimeline = computed(() => (
page.isShippingNoticeAgent
&& Boolean(
page.conversationId
|| page.shippingBatchSummary
|| page.shippingConversationWorkspace?.batches?.length
|| activeExtractionRunNo.value
)
&& Boolean(page.conversationId || activeExtractionRunNo.value)
));
const embeddedIframeSrc = computed(() => {
@@ -673,7 +668,7 @@ watch(() => page.currentAgentId, () => {
v-if="showShippingWorkflowTimeline"
:conversation-id="page.conversationId"
:refresh-trigger="page.workflowRefreshTrigger"
:controller="shippingWorkflow"
:controller="shippingProcessing"
/>
@@ -134,6 +134,10 @@ const shippingOrderExtractionRunNo = computed(() => {
: {};
return String(payload.order_extraction_run_no || '').trim();
});
const shippingOrderExtractionReadonly = computed(() => (
shippingOrderExtractionState.value?.isCurrent === false
|| Boolean(shippingOrderExtractionState.value?.supersedingRunNo)
));
/** 失败卡片复用原 Run 重试;按钮本地防重,成功后状态卡由 Run 轮询原位更新。 */
const retryShippingOrderExtraction = async () => {
if (!shippingOrderExtractionRunNo.value || retryingOrderExtraction.value) return;
@@ -690,6 +694,8 @@ function handleInlineDownload(file: InlineDownloadFile): void {
v-if="shippingOrderExtractionState"
:state="shippingOrderExtractionState"
:run-no="shippingOrderExtractionRunNo"
:readonly="shippingOrderExtractionReadonly"
:readonly-reason="shippingOrderExtractionState?.readOnlyReason"
:retrying="retryingOrderExtraction"
:refreshing="refreshingOrderExtraction"
:cancelling="cancellingOrderExtraction"
@@ -0,0 +1,326 @@
<!--
features/chat/components/shipping-review/ReviewAuditTrailDrawer.vue
用途:复核 Case 业务审计时间线按需抽屉(含变更前后快照与字段差异)。
依赖:vue-i18n、listWorkspaceShippingOrderReviewAuditTimeline。
逻辑:open 时拉取第一页;展开优先展示业务可读差异(字段名/前后值/原因);
原始 JSON 折叠为技术详情;敏感事件显示脱敏提示。
-->
<script setup lang="ts">
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { listWorkspaceShippingOrderReviewAuditTimeline } from '@/features/chat/api/shipping.api';
import type { ShippingOrderReviewAuditTimelineItem } from '@/features/chat/types/shipping.api.types';
type AuditDiffRow = {
key?: string;
path?: string;
field?: string;
label?: string;
change?: string;
before?: unknown;
after?: unknown;
};
const props = defineProps<{
open: boolean;
caseNo: string;
}>();
const emit = defineEmits<{
close: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const items = ref<ShippingOrderReviewAuditTimelineItem[]>([]);
const loading = ref(false);
const page = ref(1);
const total = ref(0);
const expandedId = ref<number | null>(null);
const pageSize = 50;
/**
* 格式化审计时间。
*/
function formatTime(value: string | null | undefined): string {
if (!value) return '—';
const date = new Date(value);
return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}
/**
* 事件类型本地化。
*/
function eventLabel(item: ShippingOrderReviewAuditTimelineItem): string {
const eventType = String(item.event_type || item.action || '').trim();
const key = `chat.shippingOrderReview.auditTrail.events.${eventType}`;
if (eventType && te(key)) return t(key);
return eventType || t('chat.shippingOrderReview.auditTrail.unknownEvent');
}
/**
* 将审计标量格式化为业务可读短文本。
*/
function formatScalar(value: unknown): string {
if (value == null || value === '') return '—';
if (typeof value === 'boolean') {
return value
? t('chat.shippingOrderReview.auditTrail.boolTrue')
: t('chat.shippingOrderReview.auditTrail.boolFalse');
}
if (typeof value === 'object') {
try {
return JSON.stringify(value);
} catch {
return String(value);
}
}
return String(value);
}
/**
* 快照/差异技术详情(原始 JSON)。
*/
function formatJson(value: unknown): string {
if (value == null) return '—';
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
/**
* 复制技术详情 JSON 到剪贴板。
*/
async function copyJson(value: unknown) {
const text = formatJson(value);
try {
await navigator.clipboard.writeText(text);
msg.success(t('chat.shippingOrderReview.auditTrail.copyDone'));
} catch {
msg.warning(t('chat.shippingOrderReview.auditTrail.copyFailed'));
}
}
/**
* 差异字段业务名称(优先 label/field,其次 path)。
*/
function diffFieldLabel(row: AuditDiffRow): string {
const label = String(row.label || row.field || row.key || row.path || '').trim();
return label || t('chat.shippingOrderReview.auditTrail.unknownField');
}
/**
* 规范化差异列表,供业务表格渲染。
*/
function normalizeDiffRows(diff: unknown): AuditDiffRow[] {
if (!Array.isArray(diff)) return [];
return diff.filter((row): row is AuditDiffRow => Boolean(row) && typeof row === 'object');
}
/**
* 切换条目展开。
*/
function toggleExpand(id: number) {
expandedId.value = expandedId.value === id ? null : id;
}
/**
* 拉取指定页审计条目并合并。
*/
async function loadPage(nextPage: number, append = false) {
if (!props.caseNo || loading.value) return;
loading.value = true;
try {
const result = await listWorkspaceShippingOrderReviewAuditTimeline(props.caseNo, {
page: nextPage,
page_size: pageSize,
});
total.value = result.total;
page.value = result.page;
items.value = append ? [...items.value, ...result.items] : result.items;
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.auditTrail.loadFailed'));
msg.warning(message);
} finally {
loading.value = false;
}
}
/**
* 打开抽屉时重置并加载第一页。
*/
watch(
() => [props.open, props.caseNo] as const,
([isOpen, caseNo]) => {
if (!isOpen || !caseNo) return;
items.value = [];
page.value = 1;
total.value = 0;
expandedId.value = null;
void loadPage(1, false);
},
);
/**
* 加载下一页。
*/
function loadMore() {
if (items.value.length >= total.value) return;
void loadPage(page.value + 1, true);
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-slate-900/30"
data-testid="review-audit-trail-drawer"
@click.self="emit('close')"
>
<aside class="flex h-full w-full max-w-xl flex-col bg-white shadow-xl dark:bg-slate-900">
<header class="flex items-center justify-between gap-2 border-b border-slate-200 px-4 py-3 dark:border-slate-800">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.auditTrail.title') }}</h2>
<p class="text-[11px] text-muted">{{ t('chat.shippingOrderReview.auditTrail.subtitle') }}</p>
</div>
<button
type="button"
class="rounded border border-slate-300 px-2 py-1 text-xs hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-trail-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<p v-if="loading && !items.length" class="text-sm text-muted">
{{ t('chat.shippingOrderReview.auditTrail.loading') }}
</p>
<p v-else-if="!items.length" class="text-sm text-muted">
{{ t('chat.shippingOrderReview.auditTrail.empty') }}
</p>
<ol v-else class="space-y-3">
<li
v-for="item in items"
:key="item.id"
class="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-950/40"
:data-testid="`review-audit-item-${item.id}`"
>
<button
type="button"
class="flex w-full flex-wrap items-center justify-between gap-2 text-left"
@click="toggleExpand(item.id)"
>
<span class="font-medium text-primary">{{ eventLabel(item) }}</span>
<time class="text-[10px] text-muted">{{ formatTime(item.created_at) }}</time>
</button>
<div class="mt-1 space-y-0.5 text-muted">
<p v-if="item.actor_display || item.actor_type">
{{ t('chat.shippingOrderReview.auditTrail.actor', {
actor: item.actor_display || item.actor_type || '—',
}) }}
</p>
<p v-if="item.task_no">
{{ t('chat.shippingOrderReview.auditTrail.taskNo', { taskNo: item.task_no }) }}
</p>
<p v-if="item.result">
{{ t('chat.shippingOrderReview.auditTrail.result', { result: item.result }) }}
</p>
<p v-if="item.error_code" class="text-rose-700 dark:text-rose-300">
{{ item.error_code }}
</p>
<p v-if="item.reason" class="text-secondary">{{ item.reason }}</p>
</div>
<div
v-if="expandedId === item.id"
class="mt-2 space-y-2 border-t border-slate-200 pt-2 dark:border-slate-800"
data-testid="review-audit-item-details"
>
<p v-if="item.sensitive_redacted" class="text-amber-800 dark:text-amber-200">
{{ t('chat.shippingOrderReview.auditTrail.sensitiveRedacted') }}
</p>
<template v-else>
<div v-if="normalizeDiffRows(item.diff).length" data-testid="review-audit-business-diff">
<p class="mb-1 font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.diff') }}
</p>
<ul class="space-y-1.5">
<li
v-for="(row, idx) in normalizeDiffRows(item.diff)"
:key="idx"
class="rounded bg-white px-2 py-1.5 text-[11px] dark:bg-slate-900"
>
<p class="font-medium text-primary">{{ diffFieldLabel(row) }}</p>
<p class="mt-0.5 text-muted">
{{ t('chat.shippingOrderReview.auditTrail.beforeValue') }}:
<span class="text-secondary">{{ formatScalar(row.before) }}</span>
</p>
<p class="text-muted">
{{ t('chat.shippingOrderReview.auditTrail.afterValue') }}:
<span class="text-secondary">{{ formatScalar(row.after) }}</span>
</p>
</li>
</ul>
</div>
<p v-if="item.reason" class="text-[11px] text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.reason') }}:{{ item.reason }}
</p>
<details class="rounded border border-slate-200 dark:border-slate-800">
<summary class="cursor-pointer px-2 py-1 text-[11px] text-muted">
{{ t('chat.shippingOrderReview.auditTrail.technicalDetails') }}
</summary>
<div class="space-y-2 border-t border-slate-200 p-2 dark:border-slate-800">
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.before') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-copy-before"
@click="copyJson(item.before_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.before_snapshot) }}</pre>
<div class="flex items-center justify-between gap-2">
<p class="font-medium text-secondary">
{{ t('chat.shippingOrderReview.auditTrail.after') }}
</p>
<button
type="button"
class="rounded border border-slate-300 px-1.5 py-0.5 text-[11px] hover:bg-slate-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-copy-after"
@click="copyJson(item.after_snapshot)"
>
{{ t('chat.shippingOrderReview.auditTrail.copyJson') }}
</button>
</div>
<pre class="max-h-32 overflow-auto rounded bg-white p-2 text-xs leading-relaxed dark:bg-slate-900">{{ formatJson(item.after_snapshot) }}</pre>
</div>
</details>
</template>
</div>
</li>
</ol>
<button
v-if="items.length < total"
type="button"
class="mt-3 w-full rounded border border-slate-300 px-2 py-1.5 text-xs hover:bg-slate-50 disabled:opacity-50 dark:border-slate-600 dark:hover:bg-slate-800"
data-testid="review-audit-trail-load-more"
:disabled="loading"
@click="loadMore"
>
{{ loading ? t('chat.shippingOrderReview.auditTrail.loading') : t('chat.shippingOrderReview.auditTrail.loadMore') }}
</button>
</div>
</aside>
</div>
</template>
@@ -0,0 +1,57 @@
/**
* features/chat/components/shipping-review/ReviewAutomationStatusPanel.spec.ts
* 用途:锁定自动处理状态仅在建单后展示,并保持阶段顺序一致。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:上游未开始时,下游即使后端旧投影为 passed 也按未开始展示。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewAutomationStatusPanel from './ReviewAutomationStatusPanel.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: {
shippingOrderReview: {
automationStatus: {
title: '自动处理状态',
subtitle: '状态',
statuses: { not_started: '未开始', passed: '已通过' },
},
},
},
},
},
});
const processGate = {
execution_no: 'EX-1',
status: 'pending',
gates_track: [
{ gate_code: 'document', label: '文档解析', status: 'not_started', sequence_no: 1 },
{ gate_code: 'reservation', label: '预约校验', status: 'passed', sequence_no: 2 },
],
};
describe('ReviewAutomationStatusPanel', () => {
it('stays hidden before a ShippingTask is created', () => {
const wrapper = mount(ReviewAutomationStatusPanel, {
props: { processGate, taskCreated: false },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-automation-status-panel"]').exists()).toBe(false);
});
it('does not show a downstream stage as passed when its upstream stage has not started', () => {
const wrapper = mount(ReviewAutomationStatusPanel, {
props: { processGate, taskCreated: true },
global: { plugins: [i18n] },
});
expect(wrapper.text()).toContain('预约校验');
expect(wrapper.text()).not.toContain('已通过');
expect(wrapper.text().match(/未开始/g)).toHaveLength(2);
});
});
@@ -0,0 +1,107 @@
<!--
features/chat/components/shipping-review/ReviewAutomationStatusPanel.vue
用途:复核工作台「自动处理状态」只读区(技术 Gate 进度,禁止业务用户点技术重试)。
依赖:vue-i18n、ShippingProcessGateUserSummary。
逻辑:仅在任务已创建后展示 gates_track;按 sequence_no 排序,并在首个未完成阶段后
抑制矛盾的下游“已通过”,不提供技术写操作。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingProcessGateUserSummary } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
processGate: ShippingProcessGateUserSummary | null | undefined;
taskCreated?: boolean;
}>();
const { t, te } = useI18n();
const track = computed(() => {
if (!props.taskCreated) return [];
const ordered = [...(props.processGate?.gates_track || [])]
.sort((left, right) => Number(left.sequence_no || 0) - Number(right.sequence_no || 0));
let upstreamReached = true;
return ordered.map((item) => {
const status = String(item.status || 'not_started');
const normalizedStatus = upstreamReached ? status : 'not_started';
if (!['passed', 'skipped'].includes(status)) upstreamReached = false;
return { ...item, status: normalizedStatus };
});
});
const visible = computed(() => track.value.length > 0);
const technicalOnly = computed(() => Boolean(
(props.processGate as { technical_auto_only?: boolean } | null | undefined)?.technical_auto_only,
));
/**
* Gate 状态本地化标签。
*/
function statusLabel(status: string): string {
const key = `chat.shippingOrderReview.automationStatus.statuses.${status}`;
return te(key) ? t(key) : status;
}
/**
* 状态点样式。
*/
function statusClass(status: string): string {
const s = String(status || '');
if (s === 'passed' || s === 'skipped') {
return 'bg-emerald-500';
}
if (s === 'running' || s === 'queued') {
return 'bg-sky-500 animate-pulse';
}
if (s === 'blocked_manual' || s === 'blocked_retryable' || s === 'waiting_external') {
return 'bg-amber-500';
}
if (s === 'failed_terminal') {
return 'bg-rose-500';
}
return 'bg-slate-300 dark:bg-slate-600';
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-automation-status-panel"
>
<header class="mb-2">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.automationStatus.title') }}</h2>
<p class="mt-0.5 text-xs text-muted">{{ t('chat.shippingOrderReview.automationStatus.subtitle') }}</p>
</header>
<ol class="space-y-1.5">
<li
v-for="item in track"
:key="String(item.gate_code)"
class="flex items-center gap-2 text-[11px] text-secondary"
>
<span
class="inline-block h-2 w-2 shrink-0 rounded-full"
:class="statusClass(String(item.status || ''))"
aria-hidden="true"
/>
<span class="min-w-0 flex-1 truncate">{{ item.label || item.gate_code }}</span>
<span class="shrink-0 text-muted">{{ statusLabel(String(item.status || '')) }}</span>
</li>
</ol>
<p
v-if="technicalOnly"
class="mt-2 text-[11px] text-muted"
data-testid="review-automation-technical-hint"
>
{{ t('chat.shippingOrderReview.automationStatus.technicalHint') }}
</p>
<p
v-else-if="processGate?.blocking_message"
class="mt-2 text-[11px] text-amber-900 dark:text-amber-100"
>
{{ processGate.blocking_message }}
</p>
</section>
</template>
@@ -0,0 +1,90 @@
/**
* features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.spec.ts
* 用途:锁定完整检查必须展示具体冲突字段、行号、来源和值。
* 依赖:vitest、@vue/test-utils、vue-i18n。
* 逻辑:field_conflict issue 不再输出笼统问题;专用冲突投影负责完整展示。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewBuildEligibilityDetailsDrawer from './ReviewBuildEligibilityDetailsDrawer.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
chat: { shippingOrderReview: {
line: '第 {index} 行',
buildEligibility: {
overallResult: '整单结果', canBuildYes: '可建单', canBuildNo: '待处理',
manualConfirmOnly: '需人工确认', blockReasons: { unknown: '未知阻断' },
routingStatus: { unknown: '未知' },
},
workbench: {
fullChecksTitle: '完整订单检查', close: '关闭', issueDetails: '问题明细',
conflictFields: '字段冲突明细', conflictDetailsPending: '冲突明细尚未同步,请刷新后查看。',
requiredField: '字段', missingValue: '缺少值', noLineChecks: '暂无明细检查',
manualReview: { customer: '确认客户', lineInventory: '第 {line} 行库存', noCandidates: '无' },
},
} },
},
},
});
const eligibility = {
can_build: false,
status: 'qualified',
issues: [{ code: 'field_conflict', message: '同一字段存在不同来源值冲突' }],
line_projections: [],
};
describe('ReviewBuildEligibilityDetailsDrawer', () => {
it('lists the exact conflicting field, line, sources and values', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility,
fieldLabels: { unit_price: '单价' },
fieldConflicts: [{
conflict_key: 'unit_price:0', field_code: 'unit_price', line_index: 0,
reason: 'field_conflict',
options: [
{ value_key: '50.43', display_value: '50.43', sources: ['PDF 表格'] },
{ value_key: '51.00', display_value: '51.00', sources: ['邮件正文'] },
],
}],
},
global: { plugins: [i18n] },
});
const details = wrapper.find('[data-testid="review-eligibility-conflict-details"]');
expect(details.text()).toContain('第 1 行');
expect(details.text()).toContain('单价');
expect(details.text()).toContain('PDF 表格:50.43');
expect(details.text()).toContain('邮件正文:51.00');
expect(wrapper.find('[data-testid="review-eligibility-blocking-reasons"]').exists()).toBe(false);
});
it('shows an explicit synchronization warning when conflict detail is absent', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: { open: true, eligibility, fieldConflicts: [] },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').text())
.toContain('冲突明细尚未同步');
});
it('filters a stale conflict issue after the current order is buildable', () => {
const wrapper = mount(ReviewBuildEligibilityDetailsDrawer, {
props: {
open: true,
eligibility: { ...eligibility, can_build: true },
fieldConflicts: [],
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-eligibility-conflict-details-missing"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('同一字段存在不同来源值冲突');
});
});
@@ -2,16 +2,22 @@
features/chat/components/shipping-review/ReviewBuildEligibilityDetailsDrawer.vue
用途:完整建单检查项抽屉(逐行投影、阻断原因)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:仅在用户主动展开时挂载;关闭不写服务端审计(敏感访问审计由阶段 5 统一补齐)。
逻辑:仅在用户主动展开时挂载;字段冲突必须展开 Case.field_conflicts 的字段、行号、
来源和值,资格 issue 只作为汇总,不得用笼统文案替代冲突明细。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
open: boolean;
eligibility: ShippingOrderReviewBuildEligibility | null;
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
fieldLabels?: Record<string, string>;
/** 客户面板的权威确认事实;已确认时不得重放历史 customer_* issue。 */
customerResolved?: boolean;
}>();
const emit = defineEmits<{
@@ -41,6 +47,42 @@ function routingStatusLabel(status?: string | null): string {
return te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.routingStatus.unknown');
}
function issueLabel(issue: Record<string, unknown>): string {
const field = String(issue.field_code || issue.field_id || '').trim();
const code = String(issue.code || '').trim();
if (field) {
const label = props.fieldLabels?.[field] || field;
return `${t('chat.shippingOrderReview.workbench.requiredField')}: ${label}`;
}
const lineIndex = Number.isFinite(Number(issue.line_index)) ? Number(issue.line_index) : null;
const candidates = Array.isArray(issue.candidate_inventory_source_codes)
? issue.candidate_inventory_source_codes.map((item) => {
const sourceCode = String(item || '').trim();
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
}).filter(Boolean)
: [];
if (code === 'customer_unresolved') return t('chat.shippingOrderReview.workbench.manualReview.customer');
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
line: lineIndex + 1,
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
});
}
const key = `chat.shippingOrderReview.workbench.issueCodes.${code}`;
return code && te(key) ? t(key) : blockReasonLabel(code);
}
function missingFieldLabel(code: string): string {
const label = props.fieldLabels?.[String(code)] || code;
return `${label}:${t('chat.shippingOrderReview.workbench.missingValue')}`;
}
function conflictOptionLabel(option: { display_value?: unknown; value_key?: string; sources?: string[] }): string {
const value = String(option.display_value ?? option.value_key ?? '—').trim() || '—';
const sources = (option.sources || []).map((source) => String(source || '').trim()).filter(Boolean);
return sources.length ? `${sources.join('、')}:${value}` : value;
}
/** 异常行置顶,已通过行排后。 */
const orderedLines = computed(() => {
const lines = [...(props.eligibility?.line_projections || [])];
@@ -51,6 +93,47 @@ const orderedLines = computed(() => {
return (a.line_index ?? 0) - (b.line_index ?? 0);
});
});
/**
* 完整检查与摘要卡共用客户确认事实:服务端刷新前残留的客户 issue 不得误导用户。
*/
const effectiveIssues = computed(() => (props.eligibility?.issues || []).filter((issue) => {
if (props.customerResolved !== true) return true;
const code = String(issue.code || '').trim().toLowerCase();
const reason = String(issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
return !(
code.startsWith('customer_')
|| reason.startsWith('customer_')
|| gate === 'customer_resolution'
|| gate === 'customer_confirmed'
);
}));
/** 资格 issue 中是否声明了字段冲突。 */
const hasFieldConflictIssue = computed(() => props.eligibility?.can_build === false && effectiveIssues.value.some((issue) => {
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
return code.includes('field_conflict') || gate === 'field_conflict_resolution';
}));
/** 字段冲突由专用明细区展示,避免问题列表重复输出一句笼统说明。 */
const nonConflictIssues = computed(() => effectiveIssues.value.filter((issue) => {
const code = String(issue.code || issue.reason_code || '').trim().toLowerCase();
const gate = String(issue.owning_gate_code || '').trim().toLowerCase();
const isConflict = code.includes('field_conflict') || gate === 'field_conflict_resolution';
if (!isConflict) return true;
// 当前资格已通过且专用冲突投影为空时,这是旧 validation snapshot 残留,禁止误报。
return false;
}));
const unexplainedBlocked = computed(() => Boolean(
props.eligibility
&& props.eligibility.can_build === false
&& !effectiveIssues.value.length
&& !props.eligibility.failed_gates?.length
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
</script>
<template>
@@ -69,10 +152,94 @@ const orderedLines = computed(() => {
data-testid="review-eligibility-details-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 space-y-2 overflow-y-auto p-4">
<section
class="rounded-lg border px-3 py-2 text-xs"
:class="eligibility.can_build
? 'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/30 dark:text-emerald-100'
: 'border-amber-200 bg-amber-50 text-amber-900 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100'"
data-testid="review-eligibility-details-overall"
>
<div class="flex items-center justify-between gap-2">
<span class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.overallResult') }}</span>
<span class="rounded-full px-2 py-0.5 font-medium" :class="eligibility.can_build ? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/60 dark:text-emerald-100' : 'bg-amber-100 text-amber-900 dark:bg-amber-900/60 dark:text-amber-100'">
{{ eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo') }}
</span>
</div>
<p v-if="eligibility.can_build && eligibility.can_auto_create === false" class="mt-1">
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<div v-if="eligibility.can_build && eligibility.can_auto_create === false && (eligibility.auto_create_diagnostics?.reason_codes?.length || eligibility.auto_create_diagnostics?.failed_gates?.length)" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.buildEligibility.autoCreateFailureTitle') }}</div>
<ul class="mt-1 list-disc pl-4">
<li v-for="reason in (eligibility.auto_create_failure_reasons?.length ? eligibility.auto_create_failure_reasons.map((item) => item.message) : (eligibility.auto_create_diagnostics.reason_codes?.length ? eligibility.auto_create_diagnostics.reason_codes : eligibility.auto_create_diagnostics.failed_gates))" :key="reason">
{{ reason }}
</li>
</ul>
</div>
</section>
<section class="rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs dark:border-slate-700 dark:bg-slate-950/40">
<div v-if="eligibility.assessment?.missing_required_fields?.length" class="mt-2">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.requiredFields') }}</div>
<div class="mt-1 text-rose-700 dark:text-rose-300">
<ul class="mt-1 list-disc pl-4">
<li v-for="code in eligibility.assessment.missing_required_fields" :key="String(code)">
{{ missingFieldLabel(String(code)) }}
</li>
</ul>
</div>
</div>
<div v-if="nonConflictIssues.length" class="mt-2" data-testid="review-eligibility-blocking-reasons">
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.issueDetails') }}</div>
<ul class="mt-1 list-disc pl-4">
<li v-for="(issue, index) in nonConflictIssues" :key="index">
{{ issueLabel(issue) }}
<span v-if="issue.explainability?.message || issue.message" class="text-slate-600 dark:text-slate-300">
— {{ issue.explainability?.message || issue.message }}
</span>
</li>
</ul>
</div>
<div v-if="unexplainedBlocked" class="mt-2 rounded border border-rose-200 bg-rose-50 px-2 py-1.5 text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100" data-testid="review-eligibility-details-unexplained-block">
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
</div>
<div
v-if="props.fieldConflicts?.length"
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-rose-950 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
data-testid="review-eligibility-conflict-details"
>
<div class="font-medium">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}</div>
<ul class="mt-2 space-y-2">
<li
v-for="conflict in props.fieldConflicts"
:key="conflict.conflict_key"
class="rounded border border-rose-200 bg-white px-2 py-1.5 dark:border-rose-900 dark:bg-slate-900"
>
<div class="font-semibold">
<span v-if="conflict.line_index != null">{{ t('chat.shippingOrderReview.line', { index: conflict.line_index + 1 }) }} · </span>
{{ props.fieldLabels?.[String(conflict.field_code)] || conflict.field_code }}
</div>
<ul class="mt-1 space-y-1 font-normal">
<li v-for="(option, optionIndex) in conflict.options" :key="`${conflict.conflict_key}-${optionIndex}`">
{{ conflictOptionLabel(option) }}
</li>
</ul>
</li>
</ul>
</div>
<div
v-else-if="hasFieldConflictIssue"
class="mt-2 rounded border border-amber-300 bg-amber-50 px-2.5 py-2 text-amber-900 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-conflict-details-missing"
>
{{ t('chat.shippingOrderReview.workbench.conflictDetailsPending') }}
</div>
</section>
<article
v-for="line in orderedLines"
:key="String(line.line_key || line.line_index)"
@@ -95,7 +262,9 @@ const orderedLines = computed(() => {
>
{{
line.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
? (eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
: t('chat.shippingOrderReview.buildEligibility.linePassesOrderBlocked'))
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
}}
</span>
@@ -13,7 +13,7 @@ import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/
/**
* 挂载摘要卡。
*/
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
function mountSummary(eligibility: ShippingOrderReviewBuildEligibility, customerResolved = false) {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
@@ -32,6 +32,12 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
primaryBlock: '首要阻断原因',
blockCount: '阻断项 {count} 项',
viewFullChecks: '查看完整检查',
manualReview: {
customer: '请确认客户',
field: '请确认字段:{field}',
lineInventory: '第 {line} 行:请确认库存来源(候选:{candidates})',
noCandidates: '暂无候选',
},
},
},
},
@@ -39,7 +45,7 @@ function mountSummary(eligibility: ShippingOrderReviewBuildEligibility) {
},
});
return mount(ReviewBuildEligibilitySummary, {
props: { eligibility },
props: { eligibility, customerResolved },
global: { plugins: [i18n] },
});
}
@@ -66,4 +72,72 @@ describe('ReviewBuildEligibilitySummary', () => {
await wrapper.find('[data-testid="review-open-eligibility-details"]').trigger('click');
expect(wrapper.emitted('open-details')).toBeTruthy();
});
it('does not keep a stale customer block after the customer is confirmed', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'customer_unresolved',
severity: 'blocking',
explainability: { message: '未能识别客户' },
}],
line_projections: [{
line_key: 'L1',
line_index: 0,
can_build: false,
block_reason: 'customer_unresolved',
}],
gates: { customer_confirmed: false },
}, true);
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-eligibility-gate-checklist"]').text()).toContain('✓');
});
it('projects concrete manual review facts before falling back to generic copy', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
issues: [{
code: 'require_manual_review',
severity: 'blocking',
line_index: 1,
candidate_inventory_source_codes: ['WH_A', 'WH_B'],
}],
line_projections: [],
inventory_source_labels: { WH_A: '华东仓', WH_B: '华南仓' },
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
.toContain('第 2 行:请确认库存来源(候选:华东仓、华南仓)');
});
it('explains a blocked order even when the API has no issue detail', () => {
const wrapper = mountSummary({
can_build: false,
status: 'blocked',
failed_gates: ['required_fields_complete'],
issues: [],
line_projections: [],
});
expect(wrapper.find('[data-testid="review-eligibility-primary-block"]').text())
.toContain('未知问题');
expect(wrapper.text()).not.toContain('required_fields_complete');
});
it('does not expose internal build and auto-create layer names', () => {
const wrapper = mountSummary({
can_build: true,
can_auto_create: false,
status: 'qualified',
issues: [],
line_projections: [],
});
expect(wrapper.find('[data-testid="review-eligibility-layers"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('can_build');
expect(wrapper.text()).not.toContain('can_auto_create');
});
});
@@ -2,19 +2,34 @@
features/chat/components/shipping-review/ReviewBuildEligibilitySummary.vue
用途:复核摘要侧栏的建单资格压缩卡(可建单状态、门禁清单、首要阻断)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility。
逻辑:展示客户确认等关键门禁勾选;「查看完整检查」emit open-details;完整逐行结果不常驻。
逻辑:只展示业务结论、具体字段/明细问题与异常导航;隐藏 Gate code、
can_build/can_auto_create 等实现标识;「查看完整检查」emit open-details。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
eligibility: ShippingOrderReviewBuildEligibility | null;
fieldConflicts?: ShippingOrderReviewFieldConflict[] | null;
fieldLabels?: Record<string, string>;
customerResolved?: boolean;
/** 可定位异常总数;由工作台统一收集草稿与门禁问题。 */
exceptionCount?: number;
/** 当前定位异常序号;未定位时为 0。 */
exceptionOrdinal?: number;
/**
* 为 true 时只展示能否建单/自动建单与异常导航,隐藏门禁清单与首要阻断文案,
* 避免与 ProcessGateRecoveryCard 重复表达同一业务阻断。
*/
focusBuildability?: boolean;
}>();
const emit = defineEmits<{
'open-details': [];
'navigate-exception': [delta: -1 | 1];
}>();
const { t, te } = useI18n();
@@ -29,28 +44,84 @@ const CHECKLIST_GATES = [
] as const;
/** 阻断 issue 数量(优先 blocking severity)。 */
const blockingIssueCount = computed(() => {
const effectiveIssues = computed(() => {
const issues = props.eligibility?.issues || [];
if (props.customerResolved !== true) return issues;
return issues.filter((item) => {
const code = String(item.code || '').trim().toLowerCase();
const reason = String(item.reason_code || '').trim().toLowerCase();
const gate = String(item.owning_gate_code || '').trim().toLowerCase();
return !(
code.startsWith('customer_')
|| reason.startsWith('customer_')
|| gate === 'customer_resolution'
|| gate === 'customer_confirmed'
);
});
});
const blockingIssueCount = computed(() => {
const issues = effectiveIssues.value;
const blocking = issues.filter((item) => String(item.severity || '') === 'blocking');
return blocking.length || issues.length;
});
/** 首要阻断文案。 */
const primaryBlockMessage = computed(() => {
const issues = props.eligibility?.issues || [];
const issues = effectiveIssues.value;
const primary = issues.find((item) => String(item.severity || '') === 'blocking') || issues[0];
if (!primary) {
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => line.can_build === false);
if (!blockedLines.length) return '';
const blockedLines = (props.eligibility?.line_projections || []).filter((line) => {
if (line.can_build !== false) return false;
if (props.customerResolved !== true) return true;
const reason = String(line.block_reason || '').trim().toLowerCase();
return !reason.startsWith('customer_');
});
if (!blockedLines.length) {
const failedGate = (props.eligibility?.failed_gates || [])[0];
if (!failedGate) return '';
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
}
const reason = String(blockedLines[0]?.block_reason || '').trim();
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${reason}`;
return reason && te(key) ? t(key) : t('chat.shippingOrderReview.buildEligibility.blockReasons.unknown');
}
const code = String(primary.code || '').trim().toLowerCase();
// Draft 基础校验按冻结 Schema 返回 field_id,资格评估返回 field_code;两者都要映射,
// 否则会丢失“究竟哪个字段没有值”的事实,只剩笼统的不可建单。
const field = String(primary.field_code || primary.field_id || '').trim();
const lineIndex = Number.isFinite(Number(primary.line_index)) ? Number(primary.line_index) : null;
const candidates = Array.isArray(primary.candidate_inventory_source_codes)
? primary.candidate_inventory_source_codes.map((item) => {
const sourceCode = String(item || '').trim();
return props.eligibility?.inventory_source_labels?.[sourceCode] || sourceCode;
}).filter(Boolean)
: [];
if (code === 'customer_unresolved') {
return t('chat.shippingOrderReview.workbench.manualReview.customer');
}
if (field) {
return t('chat.shippingOrderReview.workbench.manualReview.field', {
field: props.fieldLabels?.[field] || field,
});
}
if (lineIndex !== null && (candidates.length || code === 'require_manual_review' || code.includes('inventory_source'))) {
return t('chat.shippingOrderReview.workbench.manualReview.lineInventory', {
line: lineIndex + 1,
candidates: candidates.length ? candidates.join('、') : t('chat.shippingOrderReview.workbench.manualReview.noCandidates'),
});
}
const message = String(primary.explainability?.message || primary.message || '').trim();
if (message) return message;
const code = String(primary.code || '').trim();
const key = `chat.shippingOrderReview.issueCodes.${code}`;
return code && te(key) ? t(key) : t('chat.shippingOrderReview.issueCodes.unknown');
if (code && te(key)) return t(key);
const failedGate = (props.eligibility?.failed_gates || [])[0];
if (failedGate) {
const gateKey = `chat.shippingOrderReview.buildEligibility.gates.${failedGate}`;
return te(gateKey) ? t(gateKey) : t('chat.shippingOrderReview.issueCodes.unknown');
}
return t('chat.shippingOrderReview.issueCodes.unknown');
});
/** 不可建单的行数。 */
@@ -58,6 +129,25 @@ const blockedLineCount = computed(() =>
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false).length,
);
const missingRequiredFields = computed(() => (props.eligibility?.assessment?.missing_required_fields || [])
.map((code) => props.fieldLabels?.[String(code)] || String(code)));
const conflictFields = computed(() => (props.fieldConflicts || []).map((item) => props.fieldLabels?.[String(item.field_code || '').trim()] || String(item.field_code || '').trim())
.filter(Boolean));
const lowConfidenceFields = computed(() => props.eligibility?.issues?.flatMap((issue) =>
(issue.low_confidence_fields || []).map((item) => ({
...item,
label: props.fieldLabels?.[item.field_code] || item.field_code,
})),
) || []);
const unexplainedBlocked = computed(() => Boolean(
props.eligibility
&& props.eligibility.can_build === false
&& !props.eligibility.issues?.length
&& !props.eligibility.failed_gates?.length
&& !props.eligibility.assessment?.missing_required_fields?.length
&& !(props.eligibility.line_projections || []).some((line) => line.can_build === false),
));
/**
* 门禁勾选列表:优先 gates 映射;客户未确认时强制展示失败项。
*/
@@ -66,17 +156,37 @@ const gateChecklist = computed(() => {
const failed = new Set((props.eligibility?.failed_gates || []).map(String));
const issues = props.eligibility?.issues || [];
const customerIssue = issues.some((item) => String(item.code || '').startsWith('customer_'));
return CHECKLIST_GATES.map((gate) => {
const checks = CHECKLIST_GATES.map((gate) => {
const known = Object.prototype.hasOwnProperty.call(gates, gate);
let passed = known ? Boolean(gates[gate]) : !failed.has(gate);
if (gate === 'customer_confirmed' && customerIssue) passed = false;
if (gate === 'customer_confirmed') {
passed = props.customerResolved === true ? true : (customerIssue ? false : passed);
}
if (gate === 'field_conflicts_resolved' && props.fieldConflicts) {
passed = props.fieldConflicts.length === 0;
}
if (gate === 'required_fields_complete' && props.eligibility?.assessment) {
const missing = props.eligibility.assessment.missing_required_fields || [];
const invalid = props.eligibility.assessment.invalid_lines || [];
passed = missing.length === 0 && invalid.length === 0;
}
const labelKey = `chat.shippingOrderReview.buildEligibility.gates.${gate}`;
return {
gate,
passed,
label: te(labelKey) ? t(labelKey) : gate,
label: te(labelKey) ? t(labelKey) : t('chat.shippingOrderReview.issueCodes.unknown'),
};
}).filter((item) => Object.keys(gates).length === 0 || Object.prototype.hasOwnProperty.call(gates, item.gate) || item.gate === 'customer_confirmed');
return [
{
gate: 'overall_build_result',
passed: props.eligibility?.can_build === true,
label: props.eligibility?.can_build === true
? t('chat.shippingOrderReview.buildEligibility.overallPass')
: t('chat.shippingOrderReview.buildEligibility.overallBlocked'),
},
...checks,
];
});
</script>
@@ -103,8 +213,15 @@ const gateChecklist = computed(() => {
</span>
</header>
<p
v-if="eligibility.can_build && eligibility.can_auto_create === false"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-auto-create-blocked"
>
{{ t('chat.shippingOrderReview.buildEligibility.manualConfirmOnly') }}
</p>
<ul
v-if="gateChecklist.length"
v-if="!focusBuildability && gateChecklist.length"
class="mt-2 space-y-1 text-xs"
data-testid="review-eligibility-gate-checklist"
>
@@ -119,9 +236,57 @@ const gateChecklist = computed(() => {
</span>
</li>
</ul>
<div
v-if="exceptionCount"
class="mt-2 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-exception-nav"
>
<span>
{{ t('chat.shippingOrderReview.issues') }}
<span class="ml-1 text-muted">
{{ exceptionOrdinal ? `${exceptionOrdinal}/${exceptionCount}` : `0/${exceptionCount}` }}
</span>
</span>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
data-testid="review-exception-prev"
:title="t('chat.shippingOrderReview.exceptionNav.prevHint')"
@click="emit('navigate-exception', -1)"
>
{{ t('chat.shippingOrderReview.exceptionNav.prev') }}
</button>
<button
type="button"
class="rounded border border-amber-300 px-2 py-1 text-amber-900 hover:bg-amber-100 dark:border-amber-800 dark:text-amber-100 dark:hover:bg-amber-950"
data-testid="review-exception-next"
:title="t('chat.shippingOrderReview.exceptionNav.nextHint')"
@click="emit('navigate-exception', 1)"
>
{{ t('chat.shippingOrderReview.exceptionNav.next') }}
</button>
</div>
</div>
<div v-if="missingRequiredFields.length || conflictFields.length" class="mt-2 space-y-1 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100">
<p v-if="missingRequiredFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.missingRequiredFields') }}:</span>{{ missingRequiredFields.join('、') }}</p>
<p v-if="conflictFields.length"><span class="font-semibold">{{ t('chat.shippingOrderReview.workbench.conflictFields') }}:</span>{{ [...new Set(conflictFields)].join('、') }}</p>
</div>
<div
v-if="!focusBuildability && lowConfidenceFields.length"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-low-confidence-fields"
>
<p class="font-semibold">{{ t('chat.shippingOrderReview.workbench.lowConfidenceFields') }}:</p>
<ul class="mt-1 list-disc pl-4">
<li v-for="item in lowConfidenceFields" :key="item.field_code">
{{ item.label }}({{ item.confidence == null ? '—' : `${Math.round(item.confidence * 100)}%` }},{{ t('chat.shippingOrderReview.workbench.confidenceThreshold', { threshold: Math.round(Number(item.minimum_confidence || 0) * 100) }) }})
</li>
</ul>
</div>
<div
v-if="!eligibility.can_build && primaryBlockMessage"
v-if="!focusBuildability && !eligibility.can_build && primaryBlockMessage"
class="mt-2 rounded-lg border border-amber-200 bg-amber-50 px-2.5 py-2 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-eligibility-primary-block"
>
@@ -133,6 +298,13 @@ const gateChecklist = computed(() => {
}) }}
</p>
</div>
<div
v-if="unexplainedBlocked"
class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-xs text-rose-900 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-100"
data-testid="review-eligibility-unexplained-block"
>
{{ t('chat.shippingOrderReview.buildEligibility.unexplainedBlocked') }}
</div>
<button
type="button"
@@ -0,0 +1,130 @@
<!--
features/chat/components/shipping-review/ReviewCloseFulfillmentDialog.vue
用途:关闭行级或剩余开放行的履约决定确认弹窗(原因必填)。
依赖:vue-i18n、closeWorkspaceShippingOrderReviewLineFulfillment、showReviewResumeOutcome。
逻辑:父级传入 lineKeys;空数组表示关闭全部剩余开放行;成功后 emit confirmed。
-->
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { closeWorkspaceShippingOrderReviewLineFulfillment } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
const props = defineProps<{
open: boolean;
caseNo: string;
draftVersion: number | null | undefined;
lineKeys: string[];
closeAllRemaining?: boolean;
}>();
const emit = defineEmits<{
'update:open': [value: boolean];
confirmed: [];
}>();
const { t } = useI18n();
const msg = useMessage();
const reason = ref('');
const busy = ref(false);
const title = computed(() => (
props.closeAllRemaining || !props.lineKeys.length
? t('chat.shippingOrderReview.closeFulfillment.titleAll')
: t('chat.shippingOrderReview.closeFulfillment.titleSelected', { count: props.lineKeys.length })
));
watch(
() => props.open,
(isOpen) => {
if (!isOpen) {
reason.value = '';
busy.value = false;
}
},
);
/**
* 提交关闭履约行决定。
*/
async function onConfirm() {
const trimmed = reason.value.trim();
if (!trimmed || !props.caseNo || busy.value) return;
busy.value = true;
try {
const result = await closeWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
reason: trimmed,
line_keys: props.lineKeys.length ? props.lineKeys : undefined,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.closeFulfillment.success'),
);
emit('update:open', false);
emit('confirmed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.closeFulfillment.failed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
/**
* 取消并关闭弹窗。
*/
function onCancel() {
emit('update:open', false);
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
data-testid="review-close-fulfillment-dialog"
@click.self="onCancel"
>
<div class="w-full max-w-md rounded-xl border border-slate-200 bg-white p-4 shadow-xl dark:border-slate-800 dark:bg-slate-900">
<h2 class="text-sm font-semibold">{{ title }}</h2>
<p class="mt-1 text-xs text-muted">{{ t('chat.shippingOrderReview.closeFulfillment.subtitle') }}</p>
<label class="mt-3 block text-xs font-medium text-secondary">
{{ t('chat.shippingOrderReview.closeFulfillment.reasonLabel') }}
<textarea
v-model="reason"
rows="3"
class="mt-1 w-full rounded-md border border-default bg-surface px-2.5 py-2 text-sm"
data-testid="review-close-fulfillment-reason"
:placeholder="t('chat.shippingOrderReview.closeFulfillment.reasonPlaceholder')"
:disabled="busy"
/>
</label>
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="rounded border border-default px-3 py-1.5 text-sm hover:bg-surface-soft disabled:opacity-50"
:disabled="busy"
@click="onCancel"
>
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
<button
type="button"
class="rounded bg-rose-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-50"
data-testid="review-close-fulfillment-submit"
:disabled="busy || !reason.trim()"
@click="onConfirm"
>
{{ busy ? t('chat.shippingOrderReview.closeFulfillment.closing') : t('chat.shippingOrderReview.closeFulfillment.confirm') }}
</button>
</div>
</div>
</div>
</template>
@@ -2,7 +2,8 @@
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
逻辑:始终展示客户识别状态;选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -24,6 +25,8 @@ const props = defineProps<{
caseNo: string;
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
editable: boolean;
/** 已解决时缩为一行摘要(放入「更多状态」) */
compact?: boolean;
}>();
const emit = defineEmits<{
@@ -56,6 +59,27 @@ const displayName = computed(() => {
return name || code || String(props.resolution?.raw_name || '').trim() || '—';
});
const inputValues = computed(() => props.resolution?.input_values || []);
const candidateRows = computed(() => props.resolution?.candidates || []);
function inputLabel(definitionCode: string | null | undefined): string {
const code = String(definitionCode || '').trim().toLowerCase();
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
if (code.includes('customer') && code.includes('name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
if (code.includes('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
if (code.endsWith('customer_code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
if (code.endsWith('customer_name')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerName');
if (code.endsWith('address')) return t('chat.shippingOrderReview.customerResolution.inputLabels.address');
if (code.includes('email')) return t('chat.shippingOrderReview.customerResolution.inputLabels.email');
if (code.includes('domain')) return t('chat.shippingOrderReview.customerResolution.inputLabels.domain');
return t('chat.shippingOrderReview.customerResolution.inputLabels.other');
}
function candidateValue(candidate: unknown, key: string): string {
const row = candidate && typeof candidate === 'object' ? candidate as Record<string, unknown> : {};
return String(row[key] ?? '').trim() || '—';
}
/**
* 打开标准客户选择弹窗并加载选项。
*/
@@ -94,12 +118,21 @@ async function onConfirm(customerId: number) {
if (!props.caseNo || busy.value) return;
busy.value = true;
try {
await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
const result = await confirmWorkspaceShippingOrderReviewCustomer(props.caseNo, {
customer_id: customerId,
reason: t('chat.shippingOrderReview.customerResolution.confirmReason'),
});
dialogOpen.value = false;
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
const resume = result.resume_outcome;
if (resume?.outcome === 'auto_created' || resume?.outcome === 'idempotent_replay') {
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
taskNo: resume.task_no || '',
}));
} else if (resume?.outcome === 'waiting_manual_confirm') {
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
} else {
msg.success(t('chat.shippingOrderReview.customerResolution.confirmed'));
}
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -136,7 +169,28 @@ async function onRetry() {
<section
class="rounded-xl border border-slate-200 bg-white p-3 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-customer-resolution-panel"
:data-compact="compact && resolved ? 'true' : 'false'"
>
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
<div
v-if="compact && resolved"
class="flex flex-wrap items-center justify-between gap-2"
data-testid="review-customer-resolution-compact"
>
<p class="text-xs text-secondary">
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
<span class="mx-1 text-muted">·</span>
<span>{{ displayName }}</span>
</p>
<span
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
data-testid="review-customer-resolution-badge"
>
{{ statusLabel }}
</span>
</div>
<template v-else>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.customerResolution.title') }}</h2>
@@ -155,12 +209,26 @@ async function onRetry() {
<dl class="mt-2 space-y-1 text-xs text-secondary">
<div class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.recognizedAs') }}</dt>
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
<dd class="font-medium text-primary">{{ displayName }}</dd>
</div>
<div v-if="resolution?.raw_name && resolution.raw_name !== displayName" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.rawName') }}</dt>
<dd>{{ resolution.raw_name }}</dd>
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
</div>
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
</dd>
</div>
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
</dd>
</div>
</dl>
@@ -196,5 +264,6 @@ async function onRetry() {
@search="searchCustomers"
@confirm="onConfirm"
/>
</template>
</section>
</template>
@@ -13,6 +13,7 @@ import {
refreshWorkspaceShippingOrderReviewDuplicate,
resolveWorkspaceShippingOrderReviewDuplicate,
} from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type {
ShippingDuplicateAction,
ShippingOrderReviewDuplicate,
@@ -78,13 +79,13 @@ async function resolve(action: ShippingDuplicateAction) {
busy.value = true;
selectedAction.value = action;
try {
await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
const result = await resolveWorkspaceShippingOrderReviewDuplicate(props.caseNo, {
action,
target_task_no: target,
reason: action === 'force_create' ? forceReason.value.trim() : undefined,
});
forceReason.value = '';
msg.success(t('chat.shippingOrderReview.duplicate.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -104,8 +105,8 @@ async function onRefresh() {
if (!props.editable || !props.caseNo || busy.value) return;
busy.value = true;
try {
await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
msg.success(t('chat.shippingOrderReview.duplicate.refreshDone'));
const result = await refreshWorkspaceShippingOrderReviewDuplicate(props.caseNo);
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.duplicate.refreshDone'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -2,7 +2,8 @@
features/chat/components/shipping-review/ReviewFieldConflictPanel.vue
用途:复核工作台建单前字段冲突集中裁决区(采用候选值 / 手工值)。
依赖:vue-i18n、shipping.api.resolveWorkspaceShippingOrderReviewFieldConflict、useMessage。
逻辑:展示 Case.field_conflicts;裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
逻辑:展示 Case.field_conflicts;选项标注 evidence_role(主 PDF / 辅助 / 正文);
裁决成功后 emit refreshed;可 emit focus-conflict 定位证据。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -10,6 +11,7 @@ import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveWorkspaceShippingOrderReviewFieldConflict } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type { ShippingOrderReviewFieldConflict } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
@@ -48,6 +50,16 @@ function reasonLabel(reason: string): string {
return te(key) ? t(key) : reason;
}
/**
* 证据角色本地化(主 PDF / 辅助 / 邮件正文)。
*/
function evidenceRoleLabel(role: string | undefined | null): string {
const code = String(role || '').trim();
if (!code) return '';
const key = `chat.shippingOrderReview.fieldConflict.evidenceRole.${code}`;
return te(key) ? t(key) : code;
}
/**
* 定位冲突字段到草稿/证据区。
*/
@@ -66,13 +78,13 @@ async function adoptOption(conflict: ShippingOrderReviewFieldConflict, optionInd
if (!props.editable || !props.caseNo || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'adopt_option',
option_index: optionIndex,
expected_draft_version: props.draftVersion,
reason: t('chat.shippingOrderReview.fieldConflict.resolveReason'),
});
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -105,7 +117,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
if (!value || !props.editable || props.draftVersion == null || resolvingKey.value) return;
resolvingKey.value = conflict.conflict_key;
try {
await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
const result = await resolveWorkspaceShippingOrderReviewFieldConflict(props.caseNo, conflict.conflict_key, {
resolution: 'custom',
custom_value: value,
expected_draft_version: props.draftVersion,
@@ -113,7 +125,7 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
});
customOpenKey.value = null;
customValue.value = '';
msg.success(t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
showReviewResumeOutcome(result.resume_outcome, msg, t, t('chat.shippingOrderReview.fieldConflict.resolveSuccess'));
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
@@ -172,9 +184,22 @@ async function submitCustom(conflict: ShippingOrderReviewFieldConflict) {
:key="`${conflict.conflict_key}-${idx}`"
class="rounded border border-default bg-surface-soft px-2 py-1.5"
>
<div class="text-muted">
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
<div class="flex flex-wrap items-center gap-1 text-muted">
<span>
{{ t('chat.shippingOrderReview.fieldConflict.optionLabel', { index: idx + 1 }) }}
<span v-if="option.sources?.length" class="ml-1">({{ option.sources.join(', ') }})</span>
</span>
<span
v-if="evidenceRoleLabel(option.evidence_role)"
class="rounded px-1 py-0.5 text-[10px] font-medium"
:class="option.evidence_role === 'primary_pdf'
? 'bg-sky-100 text-sky-800 dark:bg-sky-950 dark:text-sky-200'
: 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200'"
:data-testid="`review-field-conflict-evidence-role-${idx}`"
:data-evidence-role="option.evidence_role"
>
{{ evidenceRoleLabel(option.evidence_role) }}
</span>
</div>
<div class="mt-0.5 font-mono text-primary">{{ option.display_value || option.value_key || '—' }}</div>
<button
@@ -0,0 +1,275 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentDecisionPanel.vue
用途:复核工作台行级履约决定(等待补货 / 完整行先行 / 关闭)。
依赖:vue-i18n、decide/wave line-fulfillment API、showReviewResumeOutcome。
逻辑:展示 qty/shortage;逐行决定;选中 fulfill 行可确认波次;关闭 emit open-close-dialog。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
decideWorkspaceShippingOrderReviewLineFulfillment,
waveWorkspaceShippingOrderReviewLineFulfillment,
} from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type {
ShippingOrderReviewLineFulfillment,
ShippingOrderReviewLineFulfillmentDecisionCode,
ShippingOrderReviewLineFulfillmentLine,
} from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'open-close-dialog': [lineKeys: string[]];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busyKey = ref<string | null>(null);
const selectedFulfillKeys = ref<string[]>([]);
const waveBusy = ref(false);
const TERMINAL_STATUSES = new Set(['task_created', 'fulfilled', 'closed_unfulfillable']);
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage,
));
const openLines = computed(() => (props.lineFulfillment?.lines || []).filter(
(line) => !TERMINAL_STATUSES.has(String(line.line_status || '')),
));
/**
* 行状态本地化。
*/
function lineStatusLabel(status: string | null | undefined): string {
const normalized = String(status || 'pending_decision').trim();
const key = `chat.shippingOrderReview.fulfillmentDecision.lineStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 切换 fulfill 波次选中行。
*/
function toggleFulfillSelection(lineKey: string, checked: boolean) {
const set = new Set(selectedFulfillKeys.value);
if (checked) set.add(lineKey);
else set.delete(lineKey);
selectedFulfillKeys.value = [...set];
}
/**
* 行是否可选入 fulfill 波次。
*/
function canSelectForWave(line: ShippingOrderReviewLineFulfillmentLine): boolean {
if (TERMINAL_STATUSES.has(String(line.line_status || ''))) return false;
return Boolean(line.can_fulfill_complete_line);
}
/**
* 写入单行履约决定。
*/
async function onDecide(
line: ShippingOrderReviewLineFulfillmentLine,
decisionCode: ShippingOrderReviewLineFulfillmentDecisionCode,
) {
if (!props.caseNo || !props.editable || busyKey.value) return;
if (decisionCode === 'close_unfulfillable') {
emit('open-close-dialog', [line.line_key]);
return;
}
busyKey.value = line.line_key;
try {
const result = await decideWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_key: line.line_key,
decision_code: decisionCode,
expected_draft_version: props.draftVersion ?? undefined,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.decideSuccess'),
);
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.decideFailed'));
msg.warning(message);
} finally {
busyKey.value = null;
}
}
/**
* 为选中完整行创建履约波次 Task。
*/
async function onConfirmWave() {
if (!props.caseNo || props.draftVersion == null || waveBusy.value || !selectedFulfillKeys.value.length) return;
waveBusy.value = true;
try {
const idempotencyKey = `review-wave-${props.caseNo}-${Date.now()}-${selectedFulfillKeys.value.sort().join(',')}`;
const result = await waveWorkspaceShippingOrderReviewLineFulfillment(props.caseNo, {
line_keys: [...selectedFulfillKeys.value],
expected_draft_version: props.draftVersion,
idempotency_key: idempotencyKey,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.fulfillmentDecision.waveSuccess', {
taskNo: result.task_no || '',
}),
);
selectedFulfillKeys.value = [];
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.fulfillmentDecision.waveFailed'));
msg.warning(message);
} finally {
waveBusy.value = false;
}
}
/**
* 打开关闭剩余行对话框(全部开放行)。
*/
function onCloseRemaining() {
const keys = openLines.value.map((line) => line.line_key);
emit('open-close-dialog', keys);
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-decision-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.subtitle') }}
</p>
</div>
<span class="rounded-full bg-sky-100 px-2.5 py-1 text-xs font-medium text-sky-900 dark:bg-sky-950 dark:text-sky-100">
{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: lineFulfillment?.open_count ?? openLines.length }) }}
</span>
</header>
<div class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.waveSelect') }}</th>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.partNumber') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.qty') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.status') }}</th>
<th v-if="editable" class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.fulfillmentDecision.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lineFulfillment?.lines || []"
:key="line.line_key"
class="border-t border-sky-100 dark:border-sky-900"
>
<td v-if="editable" class="px-1 py-1">
<input
v-if="canSelectForWave(line)"
type="checkbox"
class="rounded border-default"
:checked="selectedFulfillKeys.includes(line.line_key)"
:data-testid="`review-fulfill-select-${line.line_key}`"
@change="toggleFulfillSelection(line.line_key, ($event.target as HTMLInputElement).checked)"
>
</td>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono">{{ line.part_number || line.reservation_id || '—' }}</td>
<td class="px-1 py-1">
{{ line.required_qty ?? '—' }}
<span v-if="line.available_qty" class="text-muted"> / {{ line.available_qty }}</span>
</td>
<td class="px-1 py-1" :class="line.shortage_qty ? 'font-medium text-rose-700 dark:text-rose-300' : ''">
{{ line.shortage_qty || '—' }}
</td>
<td class="px-1 py-1">{{ lineStatusLabel(line.line_status) }}</td>
<td v-if="editable && !TERMINAL_STATUSES.has(String(line.line_status || ''))" class="px-1 py-1">
<div class="flex flex-wrap gap-1">
<button
type="button"
class="rounded border border-sky-300 px-2 py-1 text-xs hover:bg-sky-100 disabled:opacity-50 dark:border-sky-800 dark:hover:bg-sky-950"
:disabled="busyKey != null"
@click="onDecide(line, 'wait_inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.waitInventory') }}
</button>
<button
v-if="line.can_fulfill_complete_line"
type="button"
class="rounded border border-emerald-300 px-2 py-1 text-xs hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-800 dark:hover:bg-emerald-950"
:disabled="busyKey != null"
@click="onDecide(line, 'fulfill_complete_line_now')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.fulfillNow') }}
</button>
<button
type="button"
class="rounded border border-rose-300 px-2 py-1 text-xs text-rose-800 hover:bg-rose-50 disabled:opacity-50 dark:border-rose-800 dark:text-rose-200 dark:hover:bg-rose-950"
:disabled="busyKey != null"
@click="onDecide(line, 'close_unfulfillable')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeLine') }}
</button>
</div>
</td>
<td v-else-if="editable" class="px-1 py-1 text-muted">—</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl bg-emerald-600 px-3 py-1.5 text-sm font-medium text-white disabled:opacity-60"
data-testid="review-fulfillment-confirm-wave"
:disabled="waveBusy || !selectedFulfillKeys.length || draftVersion == null"
@click="onConfirmWave"
>
{{ waveBusy
? t('chat.shippingOrderReview.fulfillmentDecision.waving')
: t('chat.shippingOrderReview.fulfillmentDecision.confirmWave', { count: selectedFulfillKeys.length }) }}
</button>
<button
v-if="openLines.length"
type="button"
class="rounded-xl border border-rose-300 bg-white px-3 py-1.5 text-sm text-rose-800 hover:bg-rose-50 disabled:opacity-60 dark:border-rose-800 dark:bg-slate-900 dark:text-rose-200"
data-testid="review-fulfillment-close-remaining"
:disabled="waveBusy || busyKey != null"
@click="onCloseRemaining"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.closeRemaining') }}
</button>
</div>
</section>
</template>
@@ -0,0 +1,65 @@
<!--
features/chat/components/shipping-review/ReviewFulfillmentSummaryCard.vue
用途:复核侧栏紧凑展示行级履约缺口摘要,完整表格在库存模式主区处理。
依赖:vue-i18n、ShippingOrderReviewLineFulfillment。
逻辑:仅显示开放行/缺口计数与进入库存处理入口;不渲染 7 列表格。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewLineFulfillment } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lineFulfillment: ShippingOrderReviewLineFulfillment | null | undefined;
}>();
const emit = defineEmits<{
'enter-inventory': [];
}>();
const { t } = useI18n();
const visible = computed(() => Boolean(
props.lineFulfillment?.has_open_lines
|| props.lineFulfillment?.has_shortage
|| (props.lineFulfillment?.open_count || 0) > 0,
));
const openCount = computed(() => Number(props.lineFulfillment?.open_count || 0));
const readyCount = computed(() => Number(props.lineFulfillment?.ready_count || 0));
const shortageCount = computed(() => (
props.lineFulfillment?.lines || []
).filter((line) => Boolean(line.shortage_qty)).length);
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-sky-200 bg-sky-50/70 p-3 shadow-sm dark:border-sky-900 dark:bg-sky-950/40"
data-testid="review-fulfillment-summary-card"
>
<header class="mb-2">
<h2 class="text-sm font-semibold text-sky-950 dark:text-sky-50">
{{ t('chat.shippingOrderReview.fulfillmentDecision.title') }}
</h2>
<p class="mt-0.5 text-xs text-sky-900 dark:text-sky-200">
{{ t('chat.shippingOrderReview.fulfillmentDecision.railHint') }}
</p>
</header>
<ul class="space-y-1 text-xs text-secondary">
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.openCount', { count: openCount }) }}</li>
<li>{{ t('chat.shippingOrderReview.fulfillmentDecision.readyCount', { count: readyCount }) }}</li>
<li v-if="shortageCount">
{{ t('chat.shippingOrderReview.fulfillmentDecision.shortageCount', { count: shortageCount }) }}
</li>
</ul>
<button
type="button"
class="mt-3 w-full rounded-xl border border-sky-300 bg-white px-3 py-1.5 text-sm text-sky-950 hover:bg-sky-100 dark:border-sky-800 dark:bg-slate-900 dark:text-sky-50 dark:hover:bg-sky-950"
data-testid="review-fulfillment-enter-inventory"
@click="emit('enter-inventory')"
>
{{ t('chat.shippingOrderReview.fulfillmentDecision.enterInventory') }}
</button>
</section>
</template>
@@ -11,6 +11,10 @@ import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/featur
defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/**
* 仅展示「进入库存」入口,不列出行明细(Gate/履约摘要已表达缺口时使用)。
*/
summaryOnly?: boolean;
}>();
const emit = defineEmits<{
@@ -48,7 +52,7 @@ function blockReasonLabel(reason?: string | null): string {
{{ t('chat.shippingOrderReview.workbench.enterInventory') }}
</button>
</header>
<ul class="space-y-1.5">
<ul v-if="!summaryOnly" class="space-y-1.5">
<li
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
@@ -33,6 +33,8 @@ const messages = {
sourceEvidence: 'Evidence',
verbatimOk: 'OK',
verbatimFailed: 'Failed',
unavailableDisabled: 'AI suggestions are disabled in this environment.',
unavailableProvider: 'AI suggestion service is unavailable. Try again later.',
evidenceAtCell: 'page {page} {cell}',
noEvidenceCoords: 'no coords',
cancel: 'Cancel',
@@ -41,7 +43,13 @@ const messages = {
noteOptional: 'Note',
reasonRequired: 'Reason required',
evidenceLevel: { L1_field: 'Current field content', unknown: 'Relevant document content' },
status: { idle: 'Idle', pending: 'Pending', validated: 'Validated', unknown: 'Status pending confirmation' },
status: {
idle: 'Idle',
pending: 'Pending',
validated: 'Validated',
provider_unavailable: 'Unavailable',
unknown: 'Status pending confirmation',
},
decisions: { accept: 'Accept', modify: 'Modify', reject: 'Reject' },
},
},
@@ -195,4 +203,22 @@ describe('ReviewLlmSuggestionPanel', () => {
expect(wrapper.text()).not.toContain('internal_evidence_level');
wrapper.unmount();
});
it('shows a visible disabled message when Dify was not called', () => {
const unavailable: ShippingOrderReviewLlmSuggestion = {
suggestion_no: 'RSG-DISABLED',
field_id: 'fld-po',
scope: 'header',
evidence_level: 'L1_field',
status: 'provider_unavailable',
error_code: 'SHIPPING.REVIEW_LLM_DISABLED',
validation_issues: [],
};
const wrapper = mountPanel({ suggestions: [unavailable] });
expect(wrapper.get('[data-testid="review-llm-provider-unavailable"]').text())
.toContain('AI suggestions are disabled in this environment.');
expect(wrapper.text()).not.toContain('No suggestions');
wrapper.unmount();
});
});
@@ -3,7 +3,7 @@
用途:AI 建议列表与裁决内容(布局重构后作为抽屉内容组件,非常驻主区大卡片)。
依赖:vue-i18n、ReviewLlmSuggestionDialog、ShippingOrderReview* 类型。
逻辑:由 ReviewLlmSuggestionDrawer 挂载;请求须用户主动触发;仅 validated 可接受;
validation_failed 仅可拒绝;证据按 field_id + line_key/line_index 绑定。
validation_failed 仅可拒绝;provider_unavailable 明示原因;证据按 field_id + line_key/line_index 绑定。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
@@ -51,6 +51,19 @@ const failedSuggestions = computed(() =>
(props.suggestions || []).filter((item) => String(item.status || '') === 'validation_failed' && !item.decision),
);
/** Provider 未调用或调用失败的记录必须明确展示,避免用户把静默空态误认为 AI 已执行。 */
const unavailableSuggestions = computed(() =>
(props.suggestions || []).filter((item) => String(item.status || '') === 'provider_unavailable'),
);
/** 将 Provider 失败码转成可执行的业务提示,不向用户暴露底层地址或异常正文。 */
function unavailableMessage(item?: ShippingOrderReviewLlmSuggestion): string {
if (String(item?.error_code || '') === 'SHIPPING.REVIEW_LLM_DISABLED') {
return t('chat.shippingOrderReview.llmSuggestion.unavailableDisabled');
}
return t('chat.shippingOrderReview.llmSuggestion.unavailableProvider');
}
const statusLabel = computed(() => {
if (props.suggestionLoading) return t('chat.shippingOrderReview.llmSuggestion.status.pending');
const latest = (props.suggestions || [])[0];
@@ -197,7 +210,18 @@ function onDecide(payload: { decision: 'accept' | 'modify' | 'reject'; reason: s
</button>
</div>
<p v-if="!pendingSuggestions.length && !failedSuggestions.length" class="mt-3 text-xs text-slate-500">
<div
v-if="unavailableSuggestions.length"
class="mt-3 rounded border border-rose-200 bg-rose-50 px-2 py-2 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/30 dark:text-rose-300"
data-testid="review-llm-provider-unavailable"
role="alert"
>
{{ unavailableMessage(unavailableSuggestions[0]) }}
</div>
<p
v-if="!pendingSuggestions.length && !failedSuggestions.length && !unavailableSuggestions.length"
class="mt-3 text-xs text-slate-500"
>
{{ t('chat.shippingOrderReview.llmSuggestion.empty') }}
</p>
<ul v-if="pendingSuggestions.length" class="mt-3 space-y-2">
@@ -0,0 +1,182 @@
<!--
features/chat/components/shipping-review/ReviewReservationPanel.vue
用途:复核工作台 Reservation 校验摘要;展示行级有效预约号与阻断 issue。
依赖:vue-i18n、revalidateWorkspaceShippingOrderReviewReservation、showReviewResumeOutcome。
逻辑:needs_attention 时展示;编辑聚焦明细行;重校验后 emit refreshed 并展示 resume 提示。
-->
<script setup lang="ts">
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { revalidateWorkspaceShippingOrderReviewReservation } from '@/features/chat/api/shipping.api';
import { showReviewResumeOutcome } from '@/features/chat/shipping-review/showReviewResumeOutcome';
import type { ShippingOrderReviewReservation } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
caseNo: string;
draftVersion: number | null | undefined;
reservation: ShippingOrderReviewReservation | null | undefined;
editable: boolean;
}>();
const emit = defineEmits<{
refreshed: [];
'focus-line': [lineIndex: number];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const busy = ref(false);
const visible = computed(() => Boolean(props.reservation?.needs_attention || props.reservation?.issues?.length));
const lines = computed(() => props.reservation?.lines || []);
const issues = computed(() => props.reservation?.issues || []);
/**
* Reservation 状态本地化。
*/
const statusLabel = computed(() => {
const status = String(props.reservation?.status || '').trim();
const key = `chat.shippingOrderReview.reservation.status.${status}`;
if (status && te(key)) return t(key);
return props.reservation?.needs_attention
? t('chat.shippingOrderReview.reservation.status.needs_attention')
: t('chat.shippingOrderReview.reservation.status.ok');
});
/**
* issue / block_reason 本地化文案。
*/
function issueLabel(code: string | null | undefined): string {
const normalized = String(code || '').trim();
if (!normalized) return t('chat.shippingOrderReview.reservation.unknownIssue');
const key = `chat.shippingOrderReview.reservation.issues.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 聚焦明细行以便编辑 reservation_id。
*/
function onFocusLine(lineIndex: number | null | undefined) {
if (lineIndex == null || !Number.isFinite(Number(lineIndex))) return;
emit('focus-line', Number(lineIndex));
}
/**
* 显式重校验 Reservation 并刷新 Case / 建单资格。
*/
async function onRevalidate() {
if (!props.caseNo || props.draftVersion == null || !props.editable || busy.value) return;
busy.value = true;
try {
const result = await revalidateWorkspaceShippingOrderReviewReservation(props.caseNo, {
expected_draft_version: props.draftVersion,
});
showReviewResumeOutcome(
result.resume_outcome,
msg,
t,
t('chat.shippingOrderReview.reservation.revalidateDone'),
);
emit('refreshed');
} catch (error: unknown) {
const message = error instanceof BusinessError
? resolveLocalizedErrorMessage(error.code, error.message)
: (error instanceof Error ? error.message : t('chat.shippingOrderReview.reservation.revalidateFailed'));
msg.warning(message);
} finally {
busy.value = false;
}
}
</script>
<template>
<section
v-if="visible"
class="rounded-xl border border-violet-200 bg-violet-50/70 p-3 shadow-sm dark:border-violet-900 dark:bg-violet-950/40"
data-testid="review-reservation-panel"
>
<header class="flex flex-wrap items-start justify-between gap-2">
<div>
<h2 class="text-sm font-semibold text-violet-950 dark:text-violet-50">
{{ t('chat.shippingOrderReview.reservation.title') }}
</h2>
<p class="mt-0.5 text-xs text-violet-900 dark:text-violet-200">
{{ t('chat.shippingOrderReview.reservation.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="reservation?.needs_attention
? 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'
: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'"
data-testid="review-reservation-badge"
>
{{ statusLabel }}
</span>
</header>
<ul v-if="issues.length" class="mt-2 space-y-1 text-xs text-violet-950 dark:text-violet-100">
<li
v-for="(issue, idx) in issues"
:key="`${issue.code}-${issue.line_index}-${idx}`"
class="rounded border border-violet-200 bg-white/90 px-2 py-1 dark:border-violet-900 dark:bg-slate-900"
>
<span v-if="issue.line_index != null">#{{ issue.line_index + 1 }} · </span>
{{ issue.message || issueLabel(issue.code) }}
</li>
</ul>
<div v-if="lines.length" class="mt-2 overflow-x-auto">
<table class="min-w-full text-left text-xs">
<thead class="text-muted">
<tr>
<th class="px-1 py-1 font-medium">#</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.reservationId') }}</th>
<th class="px-1 py-1 font-medium">{{ t('chat.shippingOrderReview.reservation.action') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="border-t border-violet-100 dark:border-violet-900"
:class="line.needs_attention ? 'bg-amber-50/80 dark:bg-amber-950/20' : ''"
>
<td class="px-1 py-1">{{ (line.line_index ?? 0) + 1 }}</td>
<td class="px-1 py-1 font-mono">
{{ line.effective_reservation_id || '—' }}
<span v-if="line.block_reason" class="ml-1 text-[10px] text-rose-600 dark:text-rose-400">
{{ issueLabel(line.block_reason) }}
</span>
</td>
<td class="px-1 py-1">
<button
v-if="editable && line.line_index != null"
type="button"
class="text-[11px] text-primary underline-offset-2 hover:underline"
data-testid="review-reservation-focus-line"
@click="onFocusLine(line.line_index)"
>
{{ t('chat.shippingOrderReview.reservation.editLine') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="editable" class="mt-3 flex flex-wrap gap-2">
<button
type="button"
class="rounded-xl border border-violet-300 bg-white px-3 py-1.5 text-sm text-violet-950 hover:bg-violet-100 disabled:opacity-60 dark:border-violet-800 dark:bg-slate-900 dark:text-violet-100 dark:hover:bg-violet-950"
data-testid="review-reservation-revalidate"
:disabled="busy || draftVersion == null"
@click="onRevalidate"
>
{{ busy ? t('chat.shippingOrderReview.reservation.revalidating') : t('chat.shippingOrderReview.reservation.revalidate') }}
</button>
</div>
</section>
</template>
@@ -41,7 +41,7 @@ const { t } = useI18n();
data-testid="review-version-history-close"
@click="emit('close')"
>
{{ t('chat.shippingOrderReview.workbench.closePdf') }}
{{ t('chat.shippingOrderReview.workbench.close') }}
</button>
</header>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
@@ -65,10 +65,10 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
</div>
</header>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingWorkflow.loading') }}</div>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingProcessing.loading') }}</div>
<template v-else>
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingWorkflow.versionHistoryNote') }}
{{ t('chat.shippingProcessing.versionHistoryNote') }}
</p>
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
@@ -88,7 +88,7 @@ function selectVersion(version: ShippingWorkflowItemVersion) {
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium">
{{ version.version_label || t('chat.shippingWorkflow.versionLabel', { version: version.version_no || '?' }) }}
{{ version.version_label || t('chat.shippingProcessing.versionLabel', { version: version.version_no || '?' }) }}
</span>
<span
v-if="version.is_current"
@@ -14,6 +14,8 @@ const props = defineProps<{
saving: boolean;
isReadOnly: boolean;
hasDraft: boolean;
/** can_build && can_auto_create 时隐藏确认按钮并展示自动推进提示 */
hideConfirmBecauseAutoGate?: boolean;
}>();
const emit = defineEmits<{
@@ -84,6 +86,13 @@ function hasAction(action: string): boolean {
</label>
</div>
<div class="order-2 flex flex-wrap items-center justify-end gap-2 sm:order-2">
<p
v-if="hideConfirmBecauseAutoGate"
class="text-xs text-muted"
data-testid="review-auto-gate-hint"
>
{{ t('chat.shippingOrderReview.buildEligibility.autoGateProgressHint') }}
</p>
<button
v-if="hasAction('validate')"
type="button"
@@ -94,7 +103,7 @@ function hasAction(action: string): boolean {
<Save class="h-4 w-4" />{{ t('chat.shippingOrderReview.saveNow') }}
</button>
<button
v-if="hasAction('confirm')"
v-if="hasAction('confirm') && !hideConfirmBecauseAutoGate"
type="button"
:disabled="saving || !canConfirmBuild"
class="rounded bg-emerald-600 px-3 py-2 text-sm font-medium text-white disabled:opacity-50"
@@ -2,7 +2,7 @@
features/chat/components/shipping-review/ReviewWorkbenchHeader.vue
用途:订单复核工作台顶栏,展示标题上下文与保存状态。
依赖:vue-i18n、lucide-vue-next。
逻辑:ShippingOrderReviewView 传入 run/workItem 上下文;emit back 与 open-version-history;不含对话上下文切换。
逻辑:ShippingOrderReviewView 传入 run/reviewProgressContext 上下文;emit back 与 open-version-history;不含对话上下文切换。
-->
<script setup lang="ts">
import { computed } from 'vue';
@@ -18,11 +18,13 @@ const props = defineProps<{
draftConflict: boolean;
isReadOnly: boolean;
showVersionHistory?: boolean;
showAuditTrail?: boolean;
}>();
const emit = defineEmits<{
back: [];
'open-version-history': [];
'open-audit-trail': [];
}>();
const { t } = useI18n();
@@ -55,6 +57,15 @@ const subtitle = computed(() => {
<h1 class="text-base font-semibold">{{ t('chat.shippingOrderReview.title') }}</h1>
<p class="truncate text-xs text-slate-500 dark:text-slate-400">{{ subtitle }}</p>
</div>
<button
v-if="showAuditTrail"
type="button"
class="rounded border border-slate-200 px-2.5 py-1.5 text-xs hover:bg-slate-50 dark:border-slate-700 dark:hover:bg-slate-800"
data-testid="review-open-audit-trail"
@click="emit('open-audit-trail')"
>
{{ t('chat.shippingOrderReview.auditTrail.open') }}
</button>
<button
v-if="showVersionHistory"
type="button"
@@ -36,6 +36,7 @@ function setMode(next: ReviewWorkbenchMode) {
</script>
<template>
<!-- 产品契约:工作台模式条始终可见,便于发现库存/证据模式入口。 -->
<div
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs dark:border-slate-800 dark:bg-slate-900"
data-testid="review-workbench-mode"
@@ -1,14 +1,17 @@
/**
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
* 用途:确认后自动进度面板节点状态与无货代上传按钮契约。
* 用途:复核统一进度面板——UnifiedProgressTrack 挂载;人工入口仅 Gate 动作。
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
* 逻辑:按 lifecycle_status 断言 done/active/pending;待登记时展示下一步说明与任务处理台入口。
* 逻辑:有 processingProjection 才渲染轨道节点;manual upload 入口需 nextActionCode;RPA 不展示人工 CTA。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewWorkflowProgressPanel from './ReviewWorkflowProgressPanel.vue';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingReviewProgressContext,
} from '@/features/chat/types/shipping.api.types';
const messages = {
en: {
@@ -16,19 +19,25 @@ const messages = {
shippingOrderReview: {
workflowProgress: {
title: 'Auto progress',
subtitle: 'Stops at waiting for manual upload registration',
subtitle: 'Advances through freight upload',
polling: 'Refreshing…',
taskNo: 'Task {taskNo}',
progressUnavailable: 'Progress unavailable — refresh the page.',
openTaskWorkbench: 'Open task workbench to register',
noUploadHint: 'Register credentials in the task workbench',
nextStepsManualUpload:
'Next: download Excel → upload on freight platform → submit evidence and receipt',
nodes: {
building_order: 'Create task',
inventory_matching: 'Match inventory',
generating_excel: 'Generate Excel',
manual_upload_pending: 'Awaiting upload registration',
},
nextStepsGeneric: 'Manual action required — follow the system prompt.',
},
},
shippingProcessing: {
panelTitle: 'Shipping processing',
status: {
automating: 'Automating',
blocked: 'Blocked',
processing: 'Processing',
},
stage: {
freight_uploading: 'Uploading to freight',
excel_generating: 'Generating Excel',
},
},
},
@@ -38,13 +47,18 @@ const messages = {
/**
* 挂载进度面板。
*/
function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskNo?: string; polling?: boolean }) {
function mountPanel(extras?: {
taskNo?: string;
polling?: boolean;
processingProjection?: Partial<ShippingProcessingProjection> | null;
}) {
const i18n = createI18n({ legacy: false, locale: 'en', messages });
return mount(ReviewWorkflowProgressPanel, {
props: {
item: item as ShippingWorkflowItem | null,
item: null as ShippingReviewProgressContext | null,
taskNo: extras?.taskNo ?? 'SN-1',
polling: extras?.polling ?? true,
processingProjection: (extras?.processingProjection || null) as ShippingProcessingProjection | null,
},
global: {
plugins: [i18n],
@@ -59,25 +73,82 @@ function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskN
}
describe('ReviewWorkflowProgressPanel', () => {
it('marks earlier nodes done and current active', () => {
const wrapper = mountPanel({ lifecycle_status: 'generating_excel', current_stage: 'generating_excel' });
expect(wrapper.get('[data-testid="review-workflow-progress-node-building_order"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-inventory_matching"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-generating_excel"]').attributes('data-state')).toBe('active');
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('pending');
it('shows unavailable state without projection', () => {
const wrapper = mountPanel({ polling: false, processingProjection: null });
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="unified-progress-track"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
});
it('renders unified track nodes from projection stage', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'processing',
stage: 'excel_generating',
sourceType: 'eml',
},
});
expect(wrapper.find('[data-testid="review-progress-unavailable"]').exists()).toBe(false);
const current = wrapper.findAll('[data-testid="unified-progress-node"]')
.find((node) => node.attributes('data-stage') === 'excel_generating');
expect(current?.attributes('data-current')).toBe('true');
expect(current?.attributes('data-state')).toBe('running');
});
it('lights freight_uploading and hides manual CTA while automating', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'automating',
stage: 'freight_uploading',
sourceType: 'eml',
},
});
const freight = wrapper.findAll('[data-testid="unified-progress-node"]')
.find((node) => node.attributes('data-stage') === 'freight_uploading');
expect(freight?.attributes('data-current')).toBe('true');
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
});
it('shows manual_upload_pending next steps and task workbench link', () => {
const wrapper = mountPanel({ lifecycle_status: 'manual_upload_pending' }, { polling: false });
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('active');
it('shows task workbench link when gate next_action is manual upload', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'blocked',
stage: 'excel_generating',
sourceType: 'eml',
currentGate: {
gateCode: 'manual_upload',
status: 'blocked',
nextActionCode: 'wait_manual_upload',
},
availableActions: ['wait_manual_upload', 'mark_manual_uploaded'],
},
});
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
expect(link.text()).toContain('Open task workbench to register');
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
expect(link.attributes('href')).toContain('SN-1');
expect(wrapper.find('[data-testid="review-upload-freight"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
});
it('does not show manual upload tip for blocked retry_freight_upload_rpa', () => {
const wrapper = mountPanel({
polling: false,
processingProjection: {
status: 'blocked',
stage: 'freight_uploading',
sourceType: 'eml',
currentGate: {
gateCode: 'freight_upload',
status: 'blocked',
nextActionCode: 'retry_freight_upload_rpa',
},
},
});
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
});
});
@@ -1,150 +1,147 @@
<!--
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
用途:复核确认后展示自动进度节点:创建任务 → 库存匹配 → 生成 Excel → 待人工上传登记。
依赖:vue-i18n、vue-router、ShippingWorkflowItem。
逻辑:ShippingOrderReviewView 在确认后挂载;按 lifecycle_status / current_stage 点亮节点;
无货代上传按钮;待登记时说明下一步并提供跳转任务处理台入口;
轮询由父级 composable 负责。
用途:复核工作台统一进度轨道(完整 15 阶密度窗口)+ Gate 下一步提示。
依赖:vue-i18n、ShippingProcessingProjection、UnifiedProgressTrack、shippingProcessingFulfillment。
逻辑:节点高亮仅读统一投影;任务台入口仅当 currentGate.nextActionCode 指人工上传。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { RouterLink } from 'vue-router';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingReviewProgressContext,
} from '@/features/chat/types/shipping.api.types';
import {
projectionRequiresManualUploadWorkbench,
} from '@/features/chat/shipping/shippingProcessingFulfillment';
import {
resolveShippingProcessingStatusLabel,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import UnifiedProgressTrack from '@/features/shipping-progress/components/UnifiedProgressTrack.vue';
const props = defineProps<{
item: ShippingWorkflowItem | null;
item: ShippingReviewProgressContext | null;
taskNo?: string | null;
polling?: boolean;
/** 统一进度投影:节点与文案的权威来源。 */
processingProjection?: ShippingProcessingProjection | null;
}>();
const { t } = useI18n();
const { t, te } = useI18n();
/** 进度节点稳定键;与 WorkflowItem lifecycle 对齐。 */
type ReviewProgressNodeKey =
| 'building_order'
| 'inventory_matching'
| 'generating_excel'
| 'manual_upload_pending';
const hasProjection = computed(() => Boolean(props.processingProjection));
const NODES: ReviewProgressNodeKey[] = [
'building_order',
'inventory_matching',
'generating_excel',
'manual_upload_pending',
];
const unifiedStatusLabel = computed(() => {
const status = props.processingProjection?.status;
if (!status) return '';
return resolveShippingProcessingStatusLabel(status, te, t);
});
/**
* 将 Item 生命周期映射到进度节点索引(0..3);未知时按建单中。
*/
function nodeIndex(status?: string | null): number {
const normalized = String(status || '').trim();
const idx = NODES.indexOf(normalized as ReviewProgressNodeKey);
if (idx >= 0) return idx;
if (['closed', 'cancelled'].includes(normalized)) return NODES.length - 1;
if (['pending_review', 'queued', 'layout_parsing', 'extracting'].includes(normalized)) return -1;
return 0;
}
const activeIndex = computed(() =>
nodeIndex(props.item?.lifecycle_status || props.item?.current_stage),
);
const showTaskWorkbenchLink = computed(() => {
const status = String(props.item?.lifecycle_status || props.item?.current_stage || '').trim();
return status === 'manual_upload_pending' && Boolean(String(props.taskNo || '').trim());
const unifiedStageLabel = computed(() => {
const stage = props.processingProjection?.stage;
if (!stage) return '';
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
});
/**
* 任务处理台路由:带 task_no,便于直接定位待登记任务。
* 仅当 Gate next_action 明确指人工上传且非 RPA 阶段时展示任务台入口。
*/
const taskWorkbenchTo = computed(() => ({
name: 'workspace-shipping-my-tasks',
query: {
task_no: String(props.taskNo || '').trim(),
},
}));
const showTaskWorkbenchLink = computed(() => {
if (!props.processingProjection) return false;
if (!projectionRequiresManualUploadWorkbench(props.processingProjection)) return false;
return Boolean(String(props.taskNo || '').trim());
});
/**
* 节点展示态:done / active / pending。
* blocked 且非人工上传时展示通用下一步提示(来自 Gate 动作 i18n)。
*/
function nodeState(index: number): 'done' | 'active' | 'pending' {
const current = activeIndex.value;
if (current < 0) return 'pending';
if (index < current) return 'done';
if (index === current) return 'active';
return 'pending';
}
const showGenericNextSteps = computed(() => {
const projection = props.processingProjection;
if (!projection || showTaskWorkbenchLink.value) return false;
const nextAction = String(projection.currentGate?.nextActionCode || '').trim();
if (!nextAction) return false;
const status = String(projection.status || '').trim().toLowerCase();
return status === 'blocked' || status === 'needs_action';
});
const genericNextStepMessage = computed(() => {
const code = String(props.processingProjection?.currentGate?.nextActionCode || '').trim();
if (code) {
const gateKey = `workspace.shippingNotice.processGate.actions.${code}`;
if (te(gateKey)) return t(gateKey);
}
return t('chat.shippingOrderReview.workflowProgress.nextStepsGeneric');
});
</script>
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
class="rounded-xl border border-default bg-surface-soft/60 p-3"
data-testid="review-workflow-progress-panel"
>
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workflowProgress.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingOrderReview.workflowProgress.title') }}
</div>
<div
v-if="hasProjection && (unifiedStatusLabel || unifiedStageLabel)"
class="mt-0.5 text-[11px] text-secondary"
data-testid="review-progress-unified-label"
>
<span v-if="unifiedStatusLabel">{{ unifiedStatusLabel }}</span>
<span v-if="unifiedStageLabel"> · {{ unifiedStageLabel }}</span>
</div>
<div
v-else-if="!hasProjection"
class="mt-0.5 text-[11px] text-amber-700 dark:text-amber-300"
data-testid="review-progress-unavailable"
>
{{ t('chat.shippingOrderReview.workflowProgress.progressUnavailable') }}
</div>
<div v-else class="mt-0.5 text-[11px] text-secondary">
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
</p>
</div>
</div>
<span
v-if="polling"
class="text-xs text-sky-700 dark:text-sky-300"
class="shrink-0 text-[11px] text-muted"
data-testid="review-workflow-progress-polling"
>
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
</span>
</header>
</div>
<div class="mt-3" data-testid="review-progress-nodes">
<UnifiedProgressTrack
:projection="processingProjection"
density="review"
/>
</div>
<div
v-if="taskNo"
class="mb-3 flex flex-wrap items-center gap-2 text-xs text-slate-600 dark:text-slate-400"
v-if="showTaskWorkbenchLink"
class="mt-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-manual-upload-next-steps"
>
<span>{{ t('chat.shippingOrderReview.workflowProgress.taskNo', { taskNo }) }}</span>
<p>{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}</p>
<RouterLink
v-if="showTaskWorkbenchLink"
:to="taskWorkbenchTo"
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
class="mt-1 inline-flex font-medium text-brand-700 underline dark:text-brand-300"
:to="{ name: 'workspace-shipping-my-tasks', query: { task_no: taskNo || undefined } }"
data-testid="review-open-task-workbench"
>
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
</RouterLink>
</div>
<ol class="space-y-2" data-testid="review-workflow-progress-nodes">
<li
v-for="(key, index) in NODES"
:key="key"
class="flex items-center gap-3 rounded-lg border px-3 py-2 text-sm"
:class="{
'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100': nodeState(index) === 'done',
'border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100': nodeState(index) === 'active',
'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400': nodeState(index) === 'pending',
}"
:data-testid="`review-workflow-progress-node-${key}`"
:data-state="nodeState(index)"
>
<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold">
{{ index + 1 }}
</span>
<span>{{ t(`chat.shippingOrderReview.workflowProgress.nodes.${key}`) }}</span>
</li>
</ol>
<p
v-if="showTaskWorkbenchLink"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-manual-upload-next-steps"
<div
v-else-if="showGenericNextSteps"
class="mt-3 rounded-md border border-default bg-surface-soft px-2.5 py-2 text-[11px] text-secondary"
data-testid="review-generic-next-steps"
>
{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}
</p>
<p
v-else
class="mt-3 text-xs text-slate-500 dark:text-slate-400"
>
{{ t('chat.shippingOrderReview.workflowProgress.noUploadHint') }}
</p>
<p>{{ genericNextStepMessage }}</p>
</div>
</section>
</template>
@@ -0,0 +1,318 @@
/**
* features/chat/components/shipping/ShippingConversationProcessingCard.spec.ts
* 用途:验收右侧任务分组卡——needs_action/processing 与短时反馈标签。
* 依赖:Vitest、Vue Test Utils、vue-i18n、ShippingConversationProcessingCard。
* 逻辑:构造 ConversationProcessingProjection;断言分组、焦点 emit;右侧不渲染 history。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import type { ConversationProcessingProjection } from '@/features/chat/types/shipping.api.types';
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function buildProjection(): ConversationProcessingProjection {
return {
summary: { total_tasks: 3, processing: 1, needs_action: 1, completed: 1, history: 0 },
focused_task_no: 'OT-PROC',
recent_task_no: 'OT-PROC',
needs_action: [{
user_task_no: 'OT-NEED',
group: 'needs_action',
status_label: 'pending_review',
file_count: 2,
run_no: 'RUN-NEED',
can_append: false,
recently_created: false,
}],
processing: [{
user_task_no: 'OT-PROC',
submission_ordinal: 2,
group: 'processing',
status_label: 'extracting',
file_count: 1,
run_no: 'RUN-PROC',
can_append: true,
recently_created: true,
focused: true,
}],
completed: [{
user_task_no: 'OT-DONE',
group: 'completed',
status_label: 'completed',
title: 'done.pdf',
file_count: 1,
run_no: 'RUN-DONE',
can_append: false,
available_actions: ['view_details'],
}],
history: [{
user_task_no: 'OT-HIST',
group: 'history',
status_label: 'completed',
file_count: 1,
run_no: 'RUN-HIST',
can_append: false,
viewed: true,
}],
};
}
describe('ShippingConversationProcessingCard', () => {
it('renders needs_action / processing / completed groups, hides history on the right panel', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-needs_action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-completed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-DONE"]').exists()).toBe(true);
expect(wrapper.text()).toContain('刚刚创建');
expect(wrapper.text()).toContain('已完成');
// UI-04:右侧不展示处理记录分组。
expect(wrapper.find('[data-testid="shipping-processing-group-history"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-task-OT-HIST"]').exists()).toBe(false);
});
it('renders multi-PDF task title instead of first filename', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'OT-MULTI',
group: 'needs_action',
status_label: 'pending_review',
title: null,
display_kind: 'multi_document_task',
document_names: ['4518838152.pdf', '4518838154.pdf'],
file_count: 2,
run_no: 'RUN-MULTI',
can_append: false,
available_actions: ['view_details', 'cancel_task'],
}],
processing: [],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('2 个 PDF');
expect(wrapper.text()).toContain('4518838152.pdf、4518838154.pdf');
expect(wrapper.text()).toContain('取消整个任务');
// 主标题不得单独伪装成首个 PDF 文件名任务。
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).not.toContain('4518838152.pdf');
});
it('shows multi-document title from authoritative projection without workflow fallback', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, total_files: 2, processing: 0, needs_action: 1, completed: 0, history: 0 },
needs_action: [{
user_task_no: 'OT-MULTI',
group: 'needs_action',
status_label: 'pending_review',
title: null,
display_kind: 'multi_document_task',
document_names: ['4518838152.pdf', '4518838154.pdf'],
file_count: 2,
run_no: 'RUN-MULTI',
can_append: false,
available_actions: ['view_details', 'cancel_task'],
objects: [],
}],
processing: [],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('订单识别任务');
expect(wrapper.text()).toContain('2 个 PDF');
const titleEl = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI"] .text-sm.font-semibold');
expect(titleEl.text()).toContain('订单识别任务');
expect(titleEl.text()).not.toContain('4518838152.pdf');
});
it('falls back to unnamed PDF instead of internal OT number', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 1, processing: 1, needs_action: 0, completed: 0, history: 0 },
needs_action: [],
processing: [{
user_task_no: 'OT-20260803-A13F95D2',
group: 'processing',
status_label: 'processing',
title: null,
file_count: 1,
run_no: 'SNER-X',
can_append: false,
}],
completed: [],
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.text()).toContain('未命名 PDF');
expect(wrapper.text()).not.toContain('20260803-A13F95D2');
});
it('emits focus only when selecting a task (not viewed)', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('[data-testid="shipping-processing-task-OT-NEED"] button').trigger('click');
expect(wrapper.emitted('focus')?.[0]).toEqual(['OT-NEED']);
expect(wrapper.emitted('viewed')).toBeUndefined();
expect(wrapper.emitted('expandFiles')).toBeUndefined();
});
it('applies visible focus ring on needs_action card when focused', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
...buildProjection(),
focused_task_no: 'OT-NEED',
},
},
global: { plugins: [i18n] },
});
await flushPromises();
const needCard = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
// 关键断言:待操作聚焦卡必须有用户可见 ring,不能只写 data-focused。
expect(needCard.attributes('data-focused')).toBe('1');
expect(needCard.classes().join(' ')).toContain('ring-brand-400');
const other = wrapper.find('[data-testid="shipping-processing-task-OT-PROC"]');
expect(other.attributes('data-focused')).toBe('0');
expect(other.classes().join(' ')).not.toContain('ring-brand-400');
});
it('emits expandFiles / collapseFiles when toggling file details', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
...buildProjection(),
needs_action: [{
...buildProjection().needs_action[0],
available_actions: ['view_details', 'open_review', 'cancel_task'],
}],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
const taskRoot = wrapper.find('[data-testid="shipping-processing-task-OT-NEED"]');
const buttons = taskRoot.findAll('button');
// 最后一个按钮是展开/收起文件详情
await buttons[buttons.length - 1].trigger('click');
expect(wrapper.emitted('expandFiles')?.[0]?.[0]).toMatchObject({ user_task_no: 'OT-NEED' });
await buttons[buttons.length - 1].trigger('click');
expect(wrapper.emitted('collapseFiles')).toBeTruthy();
});
it('renders twenty processing tasks in one top-level container', async () => {
const processing = Array.from({ length: 20 }, (_, index) => ({
user_task_no: `OT-${index}`,
group: 'processing' as const,
status_label: 'extracting',
file_count: 1,
run_no: `RUN-${index}`,
can_append: false,
}));
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: {
summary: { total_tasks: 20, processing: 20, needs_action: 0, history: 0 },
needs_action: [],
processing,
history: [],
},
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.findAll('[data-testid^="shipping-processing-task-"]')).toHaveLength(20);
expect(wrapper.findAll('[data-testid="shipping-conversation-processing-card"]')).toHaveLength(1);
});
it('renders pending order_intake work items above task groups', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection: null,
workItems: [{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-04T12:00:00Z',
currentGate: {
gateCode: 'intake_document_parse',
status: 'blocked',
nextActionCode: 'retry_parse',
blockingReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
attemptNo: 2,
},
availableActions: ['view_details', 'retry_parse'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
failureReasonCode: 'SHIPPING_NOTICE.INTAKE_PARSE_FAILED',
parseAttemptCount: 2,
assetStatus: 'ready',
},
childOrderTasks: [],
}],
},
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-group-order-intake"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-intake-SNI-1"]').exists()).toBe(true);
expect(wrapper.text()).toContain('po.pdf');
// 关键断言:失败恢复元信息(原因 / Attempt / 资产)出现在材料卡。
expect(wrapper.find('[data-testid="shipping-processing-intake-recovery"]').exists()).toBe(true);
expect(wrapper.text()).toContain('SHIPPING_NOTICE.INTAKE_PARSE_FAILED');
await wrapper.find('[data-testid="shipping-processing-intake-action-retry_parse"]').trigger('click');
expect(wrapper.emitted('intakeAction')?.[0]?.[0]).toMatchObject({
action: 'retry_parse',
item: { workItemNo: 'SNI-1' },
});
});
});
@@ -0,0 +1,686 @@
/**
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
* 用途:右侧「本次处理中」顶层任务卡——按 needs_action / processing / completed 展示。
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
* shippingProcessingLabels。
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems,禁止 Workflow fallback;
* 单 PDF 主标题用文件名,多 PDF 用「订单识别任务」;右侧不渲染 history;
* 任务级操作只消费后端 available_actions;另渲染尚未建 OT 的 order_intake 材料卡。
*/
<script setup lang="ts">
import { computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
import type {
ConversationProcessingProjection,
ConversationProcessingUserTask,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import {
createConversationProcessingUiState,
focusTaskManually,
markTaskViewed,
resetConversationProcessingUiState,
resolveFocusedTask,
shouldExpandTaskDetails,
toggleTaskDetails,
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingStatusLabel,
shippingProcessingSourceTypeKey,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
const props = defineProps<{
projection: ConversationProcessingProjection | null;
/** 统一 ShippingProcessing work_items(含 order_intake) */
workItems?: ShippingProcessingProjection[] | null;
/** 当前会话 ID;切换时重置本地焦点/展开状态 */
conversationId?: string | null;
}>();
const emit = defineEmits<{
focus: [taskNo: string];
viewed: [taskNo: string];
/** 请求展开某任务下的文件列表(由 Timeline 按 OT objects 合成) */
expandFiles: [task: ConversationProcessingUserTask];
/** 收起文件详情:父级应清空过滤并隐藏文件列表 */
collapseFiles: [];
/** 任务级权威操作(后端 available_actions) */
taskAction: [payload: { task: ConversationProcessingUserTask; action: string }];
/** Intake 级统一投影动作(如 retry_parse) */
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
}>();
const { t, te } = useI18n();
const uiState = createConversationProcessingUiState();
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
props.projection || null
));
/** 尚未建 OT、仍应展示在「待处理材料」的 Intake 工作项。 */
const pendingIntakeItems = computed((): ShippingProcessingProjection[] => {
const items = Array.isArray(props.workItems) ? props.workItems : [];
return items.filter((item) => {
if (item.workItemType !== 'order_intake') return false;
return !['completed', 'cancelled'].includes(String(item.status || ''));
});
});
const hasContent = computed(() => Boolean(
activeProjection.value
|| pendingIntakeItems.value.length,
));
const completedTasks = computed(() => activeProjection.value?.completed || []);
const focusedTaskNo = computed(() => resolveFocusedTask(uiState, {
serverFocusedTaskNo: activeProjection.value?.focused_task_no,
recentTaskNo: activeProjection.value?.recent_task_no,
}));
/**
* 切会话时重置本地焦点/展开,避免跨会话残留。
*/
watch(
() => String(props.conversationId || '').trim(),
(next, prev) => {
if (next === prev) return;
resetConversationProcessingUiState(uiState);
},
);
/**
* 点击任务卡:只聚焦,不标记正式 viewed、不强制展开文件。
* 非权威任务号仅更新本地 UI 焦点,不向后端 focus 写接口。
*/
function onSelectTask(task: ConversationProcessingUserTask) {
const taskNo = String(task.user_task_no || '').trim();
if (!taskNo) return;
focusTaskManually(uiState, taskNo, { expandDetails: false });
if (task.user_task_authoritative === false) return;
emit('focus', taskNo);
}
/**
* 切换文件详情展开;展开时通知父级过滤,收起时清空过滤。
*/
function onToggleDetails(task: ConversationProcessingUserTask) {
const taskNo = String(task.user_task_no || '').trim();
if (!taskNo) return;
toggleTaskDetails(uiState, taskNo);
if (uiState.expandedDetailTaskNo === taskNo) {
markTaskViewed(uiState, taskNo);
emit('expandFiles', task);
} else {
emit('collapseFiles');
}
}
/**
* 是否为多 PDF 任务卡(禁止用首个文件名伪装单文件任务)。
*/
function isMultiDocumentTask(task: ConversationProcessingUserTask): boolean {
if (String(task.display_kind || '').trim() === 'multi_document_task') return true;
if (Number(task.file_count || 0) > 1) return true;
return Array.isArray(task.document_names) && task.document_names.length > 1;
}
/**
* 任务主标题:单 PDF 用文件名;多 PDF 用 i18n「订单识别任务」;禁止 OT/Run 编号。
*/
function taskLabel(task: ConversationProcessingUserTask): string {
if (isMultiDocumentTask(task)) {
return t('chat.shippingProcessing.multiPdfTaskTitle');
}
const title = String(task.title || '').trim();
if (title) return title;
return t('chat.shippingProcessing.unnamedPdf');
}
/**
* 多 PDF 副标题:前两个文件名;超过两个时追加「等 N 个 PDF」。
*/
function documentNamesPreview(task: ConversationProcessingUserTask): string {
const names = (Array.isArray(task.document_names) ? task.document_names : [])
.map((name) => String(name || '').trim())
.filter(Boolean);
if (names.length <= 1) return '';
const head = names.slice(0, 2).join(t('chat.shippingProcessing.multiPdfNameSeparator'));
if (names.length === 2) return head;
return t('chat.shippingProcessing.multiPdfNamesMore', {
names: head,
count: names.length,
});
}
/**
* 文件数量文案:多 PDF 用「N 个 PDF」,单文件仍用「N 个文件」。
*/
function fileCountLabel(task: ConversationProcessingUserTask): string {
const count = Number(task.file_count || 0);
if (count <= 0) return '';
if (isMultiDocumentTask(task)) {
return t('chat.shippingProcessing.taskPdfCount', { count });
}
return t('chat.shippingProcessing.taskFiles', { count });
}
/**
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
*/
function statusLabel(task: ConversationProcessingUserTask): string {
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
}
/**
* 最近活动时间:当天仅时分;昨天带「昨天」;更早带月日。
*/
function activityLabel(task: ConversationProcessingUserTask): string {
const raw = String(task.last_activity_at || '').trim();
if (!raw) return '';
const date = new Date(raw);
if (Number.isNaN(date.getTime())) return '';
const hh = String(date.getHours()).padStart(2, '0');
const mm = String(date.getMinutes()).padStart(2, '0');
const time = `${hh}:${mm}`;
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const startOfTarget = new Date(date.getFullYear(), date.getMonth(), date.getDate());
const dayDiff = Math.round((startOfToday.getTime() - startOfTarget.getTime()) / 86400000);
if (dayDiff === 0) {
return t('chat.shippingProcessing.updatedAt', { time });
}
if (dayDiff === 1) {
return t('chat.shippingProcessing.updatedYesterday', { time });
}
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return t('chat.shippingProcessing.updatedOnDate', { date: `${month}-${day}`, time });
}
/**
* 是否高亮 needs_action 任务。
*/
function isNeedsActionHighlight(task: ConversationProcessingUserTask): boolean {
return task.group === 'needs_action';
}
/**
* 是否展开该任务的文件详情区。
*/
function isDetailsExpanded(task: ConversationProcessingUserTask): boolean {
return shouldExpandTaskDetails(uiState, task.user_task_no, {
focusedTaskNo: focusedTaskNo.value,
forceExpand: false,
});
}
/**
* 任务级可见操作:只展示后端权威动作中的业务入口。
*/
function visibleTaskActions(task: ConversationProcessingUserTask): string[] {
const actions = Array.isArray(task.available_actions) ? task.available_actions : [];
const preferred = [
'view_details',
'open_review',
'enter_manual_review',
'retry_failed_documents',
'retry_failed_attachments',
'cancel_task',
'cancel_run',
];
const seen = new Set<string>();
const result: string[] = [];
for (const code of preferred) {
if (!actions.includes(code) || seen.has(code)) continue;
// 别名去重:只保留一套展示
if (code === 'open_review' && seen.has('enter_manual_review')) continue;
if (code === 'enter_manual_review' && seen.has('open_review')) continue;
if (code === 'retry_failed_documents' && seen.has('retry_failed_attachments')) continue;
if (code === 'retry_failed_attachments' && seen.has('retry_failed_documents')) continue;
if (code === 'cancel_task' && seen.has('cancel_run')) continue;
if (code === 'cancel_run' && seen.has('cancel_task')) continue;
seen.add(code);
result.push(code);
}
return result;
}
/**
* 动作按钮文案:任务级取消在多 PDF 时明确为「取消整个任务」。
*/
function actionLabel(task: ConversationProcessingUserTask, action: string): string {
const code = String(action || '').trim();
if (
(code === 'cancel_task' || code === 'cancel_run')
&& isMultiDocumentTask(task)
) {
return t('chat.shippingProcessing.cancelEntireTask');
}
if (code === 'cancel_task' || code === 'cancel_run') {
return t('chat.shippingProcessing.cancelEntireTaskSingle');
}
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
if (te(extractionKey)) return t(extractionKey);
const aliases: Record<string, string> = {
open_review: 'chat.shippingOrderExtractionAction.enter_manual_review',
retry_failed_documents: 'chat.shippingOrderExtractionAction.retry_failed_attachments',
};
const alias = aliases[code];
if (alias && te(alias)) return t(alias);
return code;
}
/**
* 执行任务级动作:view_details 展开文件;其余交给父级。
* 非权威任务号禁止向后端 focus/viewed 写接口。
*/
function onTaskAction(task: ConversationProcessingUserTask, action: string) {
const code = String(action || '').trim();
if (!code) return;
if (code === 'view_details') {
focusTaskManually(uiState, task.user_task_no, { expandDetails: true });
markTaskViewed(uiState, task.user_task_no);
emit('expandFiles', task);
if (task.user_task_authoritative !== false) {
emit('focus', task.user_task_no);
emit('viewed', task.user_task_no);
}
return;
}
emit('taskAction', { task, action: code });
}
/**
* Intake 材料标题:文件名 / 邮件主题 / Intake 编号。
*/
function intakeTitle(item: ShippingProcessingProjection): string {
return String(
item.sourceSummary?.filename
|| item.sourceSummary?.emailSubject
|| item.workItemNo
|| '',
).trim() || item.workItemNo;
}
/**
* Intake 状态文案。
*/
function intakeStatusLabel(item: ShippingProcessingProjection): string {
return resolveShippingProcessingStatusLabel(item.status, te, t);
}
/**
* Intake 阶段文案。
*/
function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
}
/**
* Intake 来源类型文案。
*/
function intakeSourceLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingSourceTypeKey(item.sourceType);
return te(key) ? t(key) : String(item.sourceType || '');
}
/**
* Intake / OT 门禁与失败恢复元信息(Gate / Attempt / 资产状态)。
*/
function intakeRecoveryMeta(item: ShippingProcessingProjection): string[] {
const parts: string[] = [];
const gate = item.currentGate;
const reason = String(
gate?.blockingReasonCode
|| item.sourceSummary?.failureReasonCode
|| '',
).trim();
if (reason) {
parts.push(t('chat.shippingProcessing.failureReason', { code: reason }));
}
const attempt = gate?.attemptNo ?? item.sourceSummary?.parseAttemptCount;
if (attempt != null && Number(attempt) > 0) {
parts.push(t('chat.shippingProcessing.parseAttempt', { count: Number(attempt) }));
}
const assetStatus = String(item.sourceSummary?.assetStatus || '').trim();
if (assetStatus) {
const key = `chat.shippingProcessing.assetStatus.${assetStatus}`;
parts.push(te(key) ? t(key) : t('chat.shippingProcessing.assetStatusLabel', { status: assetStatus }));
}
if (gate?.gateCode) {
parts.push(t('chat.shippingProcessing.gateCode', { code: gate.gateCode }));
}
return parts;
}
/**
* Intake 可见动作(仅展示 retry_parse)。
*/
function visibleIntakeActions(item: ShippingProcessingProjection): string[] {
const actions = Array.isArray(item.availableActions) ? item.availableActions : [];
return actions.filter((code) => code === 'retry_parse');
}
/**
* Intake 动作文案。
*/
function intakeActionLabel(action: string): string {
if (action === 'retry_parse') return t('chat.shippingProcessing.retryFromFailure');
return action;
}
/**
* 触发 Intake 级动作。
*/
function onIntakeAction(item: ShippingProcessingProjection, action: string) {
const code = String(action || '').trim();
if (!code) return;
emit('intakeAction', { item, action: code });
}
</script>
<template>
<div
v-if="hasContent"
class="space-y-3"
data-testid="shipping-conversation-processing-card"
>
<section
v-if="pendingIntakeItems.length"
data-testid="shipping-processing-group-order-intake"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300">
{{ t('chat.shippingProcessing.pendingMaterials') }}
· {{ pendingIntakeItems.length }}
</div>
<div class="space-y-2">
<article
v-for="item in pendingIntakeItems"
:key="item.workItemNo"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:data-testid="`shipping-processing-intake-${item.workItemNo}`"
:data-source-type="item.sourceType"
:data-status="item.status"
>
<div class="text-sm font-semibold text-primary">
{{ intakeTitle(item) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span>{{ intakeSourceLabel(item) }}</span>
<span>{{ intakeStatusLabel(item) }}</span>
<span v-if="intakeStageLabel(item)">{{ intakeStageLabel(item) }}</span>
</div>
<div
v-if="intakeRecoveryMeta(item).length"
class="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-rose-700 dark:text-rose-300"
data-testid="shipping-processing-intake-recovery"
>
<span
v-for="(meta, idx) in intakeRecoveryMeta(item)"
:key="`${item.workItemNo}-meta-${idx}`"
>{{ meta }}</span>
</div>
<div
v-if="visibleIntakeActions(item).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-intake-actions"
>
<button
v-for="action in visibleIntakeActions(item)"
:key="`${item.workItemNo}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-intake-action-${action}`"
@click="onIntakeAction(item, action)"
>
{{ intakeActionLabel(action) }}
</button>
</div>
</article>
</div>
</section>
<section
v-if="activeProjection?.needs_action.length"
data-testid="shipping-processing-group-needs_action"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: activeProjection.needs_action.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.needs_action"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
isNeedsActionHighlight(task)
? 'border-amber-400 bg-amber-50/80 dark:border-amber-700 dark:bg-amber-950/30'
: 'border-default bg-surface',
focusedTaskNo === task.user_task_no ? 'ring-1 ring-brand-400' : '',
]"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
</div>
<div
v-else-if="task.recently_created"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
<section
v-if="activeProjection?.processing.length"
data-testid="shipping-processing-group-processing"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-sky-700 dark:text-sky-300">
{{ resolveShippingProcessingMessage('groupProcessing', te, t, { count: activeProjection.processing.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in activeProjection.processing"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
? 'ring-1 ring-brand-400'
: ''"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
<div
v-if="task.recent_append_count"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justAppended', te, t, { count: task.recent_append_count }) }}
</div>
<div
v-else-if="task.recently_created"
class="mt-1 text-[11px] font-medium text-brand-700 dark:text-brand-300"
>
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
<section
v-if="completedTasks.length"
data-testid="shipping-processing-group-completed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-emerald-700 dark:text-emerald-300">
{{ resolveShippingProcessingMessage('groupCompleted', te, t, { count: completedTasks.length }) }}
</div>
<div class="space-y-2">
<article
v-for="task in completedTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
? 'ring-1 ring-brand-400'
: ''"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
:data-focused="focusedTaskNo === task.user_task_no ? '1' : '0'"
>
<button
type="button"
class="w-full text-left"
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
</div>
<div class="mt-0.5 flex flex-wrap gap-x-2 gap-y-0.5 text-[11px] text-secondary">
<span v-if="fileCountLabel(task)">{{ fileCountLabel(task) }}</span>
<span>{{ statusLabel(task) }}</span>
<span v-if="activityLabel(task)">{{ activityLabel(task) }}</span>
</div>
<div
v-if="documentNamesPreview(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-document-names"
>
{{ documentNamesPreview(task) }}
</div>
</button>
<div
v-if="visibleTaskActions(task).length"
class="mt-1.5 flex flex-wrap gap-1.5"
data-testid="shipping-processing-task-actions"
>
<button
v-for="action in visibleTaskActions(task)"
:key="`${task.user_task_no}-${action}`"
type="button"
class="rounded-md border border-default bg-surface px-2 py-0.5 text-[11px] text-secondary hover:text-primary"
:data-testid="`shipping-processing-action-${action}`"
@click="onTaskAction(task, action)"
>
{{ actionLabel(task, action) }}
</button>
</div>
<button
type="button"
class="mt-1.5 flex items-center gap-1 text-[11px] text-secondary hover:text-primary"
@click="onToggleDetails(task)"
>
<ChevronDown v-if="isDetailsExpanded(task)" class="h-3 w-3" />
<ChevronRight v-else class="h-3 w-3" />
{{ isDetailsExpanded(task)
? t('chat.shippingProcessing.collapseFileDetails')
: t('chat.shippingProcessing.expandFileDetails') }}
</button>
</article>
</div>
</section>
</div>
</template>
@@ -2,12 +2,10 @@
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、
* orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* Run 失败优先展示 errorExplainability.message(含 request_id 提示),禁止只展示技术错误码;
* 「查看处理详情」挂载详情抽屉;抽屉内证据/复核入口携带 focus+document_id 打开复核页;
* 文档与时间线加载失败支持独立就地重试;右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗。
* orderExtractionProgressDisplay、vue-router、vue-i18n、ProcessGateRecoveryCard。
* 逻辑:回退 handling_items / primary_notice / Run summary;
* Run 失败优先展示 errorExplainability.message;详情抽屉证据入口携带 focus+document_id;
* Gate confirm_customer 经 ChatPage 打开客户选择弹窗;不再读取 Workflow 空壳 counts。
*/
<script setup lang="ts">
import { computed, inject, ref } from 'vue';
@@ -23,7 +21,6 @@ import type {
ShippingOrderExtractionDocumentResult,
ShippingOrderExtractionProgressEvent,
ShippingProcessGateUserSummary,
ShippingWorkflowItemCounts,
} from '../../types/shipping.api.types';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import {
@@ -39,7 +36,6 @@ import {
type ShippingHandlingAffectedRef,
type ShippingHandlingRefTarget,
} from '../../shipping/orderExtractionHandlingRefs';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
const props = defineProps<{
@@ -48,8 +44,9 @@ const props = defineProps<{
retrying?: boolean;
refreshing?: boolean;
cancelling?: boolean;
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
workflowSummary?: ShippingWorkflowItemCounts | null;
/** 新版 Run 已替代旧版时,历史卡仅允许查看详情。 */
readonly?: boolean;
readonlyReason?: string | null;
}>();
const emit = defineEmits<{
@@ -64,7 +61,6 @@ const router = useRouter();
const chatPage = inject(CHAT_PAGE_KEY, null);
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* Gate 恢复卡「确认客户」:打开对话叠层客户选择弹窗。
@@ -74,15 +70,9 @@ async function onGateConfirmCustomer(taskNo: string) {
}
/**
* 从 Workflow Items 中取首个阻断 Gate 摘要,供 Run 级卡片展示。
* Run 级阻断 Gate:co8 后不再从 Workflow items 读取;由复核/Gate 主路径承接。
*/
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => {
const items = injectedWorkflow?.items.value || [];
for (const item of items) {
if (item.process_gate?.current_blocking_gate) return item.process_gate;
}
return null;
});
const runLevelProcessGate = computed((): ShippingProcessGateUserSummary | null => null);
const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
@@ -97,47 +87,10 @@ const progressLoading = ref(false);
const progressLoadFailed = ref(false);
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
/**
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
*/
const unifiedCounts = computed(() => {
const fromProp = props.workflowSummary;
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
const fromInject = injectedWorkflow?.workflow.value?.counts;
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
return null;
});
const displaySummary = computed(() => props.state.summary);
const displaySummary = computed(() => {
const counts = unifiedCounts.value;
if (!counts) return props.state.summary;
return {
totalDocuments: counts.total,
processingDocuments: counts.processing,
pendingDocuments: 0,
completedDocuments: counts.completed,
reviewRequiredDocuments: counts.pending_review,
failedDocuments: counts.failed,
cancelledDocuments: 0,
candidateCount: props.state.summary.candidateCount,
openedExistingCount: props.state.summary.openedExistingCount,
};
});
const workflowStageLabel = computed(() => {
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
if (!stage) return '';
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
return te(key) ? t(key) : stage;
});
const workflowLastActivityLabel = computed(() => {
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
if (!raw) return '';
const date = new Date(String(raw));
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleString();
});
const workflowStageLabel = computed(() => '');
const workflowLastActivityLabel = computed(() => '');
const handlingItems = computed(() => props.state.handlingItems || []);
@@ -261,11 +214,15 @@ const activityKey = computed(() => {
});
const showRetry = computed(() => (
!props.readonly && (
props.state.availableActions.includes('retry_failed_attachments')
|| displaySummary.value.failedDocuments > 0
)
));
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
const showRefresh = computed(() => !props.readonly && props.state.availableActions.includes('refresh_status'));
const showCancel = computed(() => (
!props.readonly
&&
props.state.availableActions.includes('cancel_run')
&& !(props.state.cancellation?.requested && !props.state.cancellation?.completedAt)
));
@@ -404,6 +361,7 @@ function closeDetailsDrawer() {
* 从详情抽屉进入复核/证据页。
*/
async function enterReviewFromDetails(payload?: { focus?: 'evidence' | 'draft'; documentId?: number }) {
if (props.readonly) return;
await openOrderReview({
documentId: payload?.documentId,
focus: payload?.focus === 'evidence' ? 'evidence' : 'draft',
@@ -458,6 +416,7 @@ function affectedRows(item: ShippingOrderExtractionHandlingItemState) {
* @param item - 处理事项
*/
async function handleHandlingAction(item: ShippingOrderExtractionHandlingItemState) {
if (props.readonly) return;
const action = String(item.primaryAction || '').trim();
if (action === 'retry_failed_attachments') {
emit('retry');
@@ -489,6 +448,7 @@ function confirmCancel() {
/** 打开取消确认并清空上次填写的原因。 */
function openCancelConfirm() {
if (props.readonly) return;
cancelReason.value = '';
confirmCancelOpen.value = true;
}
@@ -516,6 +476,13 @@ function openCancelConfirm() {
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
<div class="min-w-0 flex-1">
<div
v-if="readonly"
class="mb-1 text-xs font-medium opacity-80"
data-testid="shipping-order-extraction-readonly"
>
{{ t('chat.shippingOrderExtractionHistory.superseded') }}
</div>
<div class="text-sm font-medium">{{ compactLine }}</div>
<p
v-if="state.errorExplainability?.request_id"
@@ -564,7 +531,7 @@ function openCancelConfirm() {
v-if="runLevelProcessGate?.current_blocking_gate"
class="mt-2"
:summary="runLevelProcessGate"
:can-handle="true"
:can-handle="!readonly"
:navigation-context="gateNavigationContext"
@refreshed="emit('refresh')"
@refresh-needed="emit('refresh')"
@@ -591,13 +558,15 @@ function openCancelConfirm() {
<span class="ml-1 opacity-80">{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}</span>
</div>
<button
v-if="item.primaryAction"
v-if="item.primaryAction && !readonly && (item.primaryAction !== 'review_candidate' || !handlingItems.some((other) => other.primaryAction === 'enter_manual_review'))"
type="button"
class="shrink-0 rounded-md border border-current/20 px-2 py-0.5 text-[11px] font-medium hover:bg-black/5 dark:hover:bg-white/5"
@click="handleHandlingAction(item)"
>
{{ te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
{{ (item.primaryAction === 'review_candidate' || item.primaryAction === 'enter_manual_review')
? t('chat.shippingOrderExtractionAction.enter_manual_review')
: te(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
? t(`chat.shippingOrderExtractionAction.${item.primaryAction}`)
: t('chat.shippingOrderExtractionAction.view_details') }}
</button>
</div>
@@ -616,6 +585,7 @@ function openCancelConfirm() {
:key="row.key"
type="button"
class="rounded border border-current/20 px-1.5 py-0.5 text-[11px] font-medium underline-offset-2 hover:underline"
:disabled="readonly"
@click="openAffectedRef(row.target)"
>
{{ row.label }}
@@ -65,21 +65,21 @@ const canReparse = computed(() => {
const reparseActionLabel = computed(() => {
if (props.item?.reparse_kind === 'failed_run_retry') {
return t('chat.shippingWorkflow.actions.retryFailedRun');
return t('chat.shippingProcessing.actions.retryFailedRun');
}
return t('chat.shippingWorkflow.actions.reparse');
return t('chat.shippingProcessing.actions.reparse');
});
const filename = computed(() => {
const name = String(props.item?.current_document_filename || '').trim();
if (name) return name;
if (!props.item) return '';
return t('chat.shippingWorkflow.filenameFallback', {
return t('chat.shippingProcessing.filenameFallback', {
docId: props.item.current_document_id,
});
});
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
const title = computed(() => t('chat.shippingProcessing.detail.title'));
/**
* 解析生命周期 / 阶段文案。
@@ -87,8 +87,8 @@ const title = computed(() => t('chat.shippingWorkflow.detail.title'));
function statusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '';
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
return te(key) ? t(key) : t('chat.shippingWorkflow.itemStatus.unknown');
const key = `chat.shippingProcessing.itemStatus.${normalized}`;
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
}
/**
@@ -97,8 +97,8 @@ function statusLabel(status?: string | null): string {
function eventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.message_code || event.event_code || '').trim();
if (!code) return '—';
const key = `chat.shippingWorkflow.event.${code}`;
return te(key) ? t(key) : t('chat.shippingWorkflow.event.unknown');
const key = `chat.shippingProcessing.event.${code}`;
return te(key) ? t(key) : t('chat.shippingProcessing.event.unknown');
}
/**
@@ -226,7 +226,7 @@ onBeforeUnmount(() => {
ref="closeButtonRef"
type="button"
class="rounded-md p-1 text-muted hover:bg-surface-muted"
:aria-label="t('chat.shippingWorkflow.detail.close')"
:aria-label="t('chat.shippingProcessing.detail.close')"
data-testid="shipping-workflow-item-drawer-close"
@click="handleClose"
>
@@ -236,41 +236,41 @@ onBeforeUnmount(() => {
<div class="min-h-0 flex-1 overflow-auto p-4">
<div v-if="loading" class="text-xs text-muted">
{{ t('chat.shippingWorkflow.loading') }}
{{ t('chat.shippingProcessing.loading') }}
</div>
<template v-else-if="item">
<dl class="space-y-2 text-xs">
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.filename') }}</dt>
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.status') }}</dt>
<dd class="font-medium text-primary">{{
statusLabel(item.display_lifecycle_status || item.lifecycle_status)
}}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.stage') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
</div>
<div v-if="item.current_run_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.runNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
</div>
<div v-if="item.current_case_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.caseNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
</div>
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.lastActivity') }}</dt>
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
</div>
<div v-if="item.closed_reason" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
<dt class="text-secondary">{{ t('chat.shippingProcessing.detail.closedReason') }}</dt>
<dd class="font-medium text-primary">
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
{{ te(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
? t(`chat.shippingProcessing.closedReason.${item.closed_reason}`)
: item.closed_reason }}
</dd>
</div>
@@ -289,7 +289,7 @@ onBeforeUnmount(() => {
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
{{ t('chat.shippingProcessing.detail.eventsTitle') }}
</h3>
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
<li
@@ -306,11 +306,11 @@ onBeforeUnmount(() => {
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
{{ t('chat.shippingProcessing.detail.eventsEmpty') }}
</p>
</section>
</template>
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
<p v-else class="text-xs text-muted">{{ t('chat.shippingProcessing.detail.empty') }}</p>
</div>
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
@@ -332,7 +332,7 @@ onBeforeUnmount(() => {
data-testid="shipping-workflow-item-drawer-cancel"
@click="emit('cancel', item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
{{ t('chat.shippingProcessing.actions.cancelFile') }}
</button>
</footer>
</aside>
@@ -32,18 +32,18 @@ const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
const title = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
? t('chat.shippingProcessing.reasonDialog.reparseTitle')
: t('chat.shippingProcessing.reasonDialog.cancelTitle')
));
const confirmLabel = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
? t('chat.shippingProcessing.reasonDialog.reparseConfirm')
: t('chat.shippingProcessing.reasonDialog.cancelConfirm')
));
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
const reasonLabel = computed(() => t('chat.shippingProcessing.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingProcessing.reasonRequired'));
/**
* 关闭弹窗并重置本地表单。
@@ -128,7 +128,7 @@ onBeforeUnmount(() => {
>
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
<p class="mt-1 text-xs text-secondary">
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
{{ t('chat.shippingProcessing.reasonDialog.impact') }}
</p>
<label class="mt-3 block text-xs text-secondary">
@@ -141,7 +141,7 @@ onBeforeUnmount(() => {
class="input-field mt-1 w-full py-1.5 text-xs"
:aria-invalid="reasonMissing"
data-testid="shipping-workflow-reason-input"
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
:placeholder="t('chat.shippingProcessing.reasonDialog.reasonPlaceholder')"
/>
</label>
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
@@ -152,7 +152,7 @@ onBeforeUnmount(() => {
v-if="action === 'reparse'"
class="mt-2 block text-xs text-secondary"
>
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
{{ t('chat.shippingProcessing.reasonDialog.commentOptional') }}
<textarea
v-model="comment"
rows="2"
@@ -169,7 +169,7 @@ onBeforeUnmount(() => {
data-testid="shipping-workflow-reason-cancel"
@click="handleCancel"
>
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
{{ t('chat.shippingProcessing.reasonDialog.dismiss') }}
</button>
<button
type="button"
@@ -179,7 +179,7 @@ onBeforeUnmount(() => {
@click="handleConfirm"
>
{{ confirmLoading
? t('chat.shippingWorkflow.reasonDialog.submitting')
? t('chat.shippingProcessing.reasonDialog.submitting')
: confirmLabel }}
</button>
</div>
@@ -1,330 +1,464 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:先展开侧栏并打开详情抽屉;断言 layout_parsing 可见;文件名优先;过滤与 cancel。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createI18n } from 'vue-i18n';
import { ref } from 'vue';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
const routerPush = vi.fn(async () => undefined);
vi.mock('vue-router', () => ({
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),
useRouter: () => ({ push: routerPush }),
}));
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'detail.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
events: [],
})),
listWorkspaceShippingWorkflows: vi.fn(),
cancelWorkspaceShippingWorkflowItem: vi.fn(),
reparseWorkspaceShippingWorkflowItem: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 10,
current_document_id: 10,
current_document_filename: 'shipping-notice.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
};
}
function buildController(
items: ShippingWorkflowItem[],
extras?: { workflows?: ShippingWorkflow[] },
): UseShippingNoticeWorkflowReturn {
const workflowList = extras?.workflows ?? [{
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
},
items,
}];
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
const workflows = ref(workflowList);
const workflow = ref(workflowList[0] || null);
const itemRef = ref(items);
return {
workflows,
selectedWorkflowNo,
selectWorkflow: vi.fn((no: string) => {
selectedWorkflowNo.value = no;
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
itemRef.value = workflow.value?.items || [];
}),
workflow,
items: itemRef,
loading: ref(false),
error: ref(null),
refresh: vi.fn(async () => undefined),
cancelItem: vi.fn(async () => null),
reparseItem: vi.fn(async () => null),
stop: vi.fn(),
};
}
/**
* 展开窄侧栏并打开详情抽屉(完整列表仅在抽屉内)。
*/
async function openDetailsDrawer(wrapper: ReturnType<typeof mount>) {
const toggleCollapse = wrapper.find('[data-testid="shipping-workflow-timeline"] button');
if (toggleCollapse.exists()) {
await toggleCollapse.trigger('click');
await flushPromises();
}
const openDetails = wrapper.find('[data-testid="shipping-workflow-toggle-details"]');
expect(openDetails.exists()).toBe(true);
await openDetails.trigger('click');
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);
}
const mountOptions = {
global: {
plugins: [i18n],
stubs: {
// 抽屉/原因框经 Teleport;单测就地渲染便于查询。
teleport: true,
},
},
};
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
routerPush.mockClear();
});
it('shows layout_parsing items with filename before review case exists', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-LAYOUT',
lifecycle_status: 'layout_parsing',
current_case_no: null,
current_document_filename: 'layout.pdf',
}),
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
expect(wrapper.text()).toContain('尚无复核单');
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
});
it('filters to actionable items when pending-only is checked', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
});
it('opens the review workspace directly for pending review items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-REVIEW-OPEN',
lifecycle_status: 'pending_review',
current_run_no: 'RUN-REVIEW-1',
current_case_no: 'CASE-REVIEW-1',
current_document_id: 42,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
name: 'Chat',
params: { agentId: 'agent-1' },
query: expect.objectContaining({
mode: 'order-review',
run_no: 'RUN-REVIEW-1',
case_no: 'CASE-REVIEW-1',
document_id: '42',
focus: 'draft',
}),
}));
});
it('cancels an item via in-app reason dialog', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(false);
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
expect(reasonInput.exists()).toBe(true);
await reasonInput.setValue('cancel reason');
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
await flushPromises();
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
reason: 'cancel reason',
expected_lock_version: 3,
});
});
it('shows batch switcher for multiple workflows', async () => {
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
const workflows = [
{
workflow_no: 'SNWF-A',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
items: itemsA,
},
{
workflow_no: 'SNWF-B',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'failed',
lock_version: 1,
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
items: itemsB,
},
];
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
});
it('shows reparse action for failed items', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-FAIL',
lifecycle_status: 'failed',
current_document_filename: 'bad.pdf',
available_actions: ['cancel', 'reparse'],
reparse_kind: 'failed_run_retry',
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
expect(wrapper.text()).toContain('重试失败识别');
});
it('hides reparse for pending_review without available_actions.reparse', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-PR',
lifecycle_status: 'pending_review',
current_case_no: null,
available_actions: ['cancel'],
reparse_kind: null,
}),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);
});
it('keeps sidebar width when opening details dialog overlay', async () => {
const controller = buildController([buildItem()]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
...mountOptions,
});
await flushPromises();
await openDetailsDrawer(wrapper);
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');
// 关键断言:弹层打开后侧栏仍固定窄宽,对话区不被列表撑开。
expect(aside.classes().join(' ')).toContain('md:w-60');
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');
expect(overlay.exists()).toBe(true);
expect(overlay.classes().join(' ')).toContain('fixed');
expect(overlay.find('[role="dialog"]').exists()).toBe(true);
});
});
/**␍
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts␍
* 用途:验证右侧「本次处理中」OT 任务卡、展开后文件明细、过滤与取消/重识别弹窗。␍
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。␍
* 逻辑:文件明细由 expandedTask.objects 经 mapUserTaskObjectsToFileRows 合成;␍
* 须先展开 processing 任务才出现文件抽屉;WF 批次切换器恒隐藏。␍
*/␍
import { mount, flushPromises } from '@vue/test-utils';␍
import { describe, expect, it, vi, beforeEach } from 'vitest';␍
import { createI18n } from 'vue-i18n';␍
import { ref } from 'vue';␍
import chatZhCn from '@/locales/zh-CN/chat.json';␍
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';␍
import type {␍
ConversationProcessingObject,␍
ConversationProcessingProjection,␍
ConversationProcessingUserTask,␍
ShippingWorkflowItem,␍
} from '../../types/shipping.api.types';␍
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';␍
␍
const routerPush = vi.fn(async () => undefined);␍
vi.mock('vue-router', () => ({␍
useRoute: () => ({ params: { agentId: 'agent-1' }, query: {} }),␍
useRouter: () => ({ push: routerPush }),␍
}));␍
␍
const api = vi.hoisted(() => ({␍
cancelRun: vi.fn(async () => ({})),␍
reparseRun: vi.fn(async () => ({})),␍
retryRun: vi.fn(async () => ({})),␍
retryIntake: vi.fn(async () => ({})),␍
}));␍
␍
vi.mock('@/features/chat/api/shipping.api', () => ({␍
cancelWorkspaceShippingOrderExtractionRun: api.cancelRun,␍
reparseWorkspaceShippingOrderExtractionRun: api.reparseRun,␍
retryWorkspaceShippingOrderExtractionRun: api.retryRun,␍
retryShippingNoticeIntake: api.retryIntake,␍
}));␍
␍
vi.mock('@/shared/composables/useMessage', () => ({␍
useMessage: () => ({␍
success: vi.fn(),␍
error: vi.fn(),␍
warning: vi.fn(),␍
info: vi.fn(),␍
}),␍
}));␍
␍
const i18n = createI18n({␍
legacy: false,␍
locale: 'zh-CN',␍
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },␍
});␍
␍
const DEFAULT_TASK_NO = 'OT-TEST';␍
␍
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {␍
return {␍
item_no: 'SWI-1',␍
workflow_no: 'SNWF-1',␍
conversation_id: 'conv-1',␍
root_document_id: 10,␍
current_document_id: 10,␍
current_document_filename: 'shipping-notice.pdf',␍
current_version_no: 1,␍
lifecycle_status: 'layout_parsing',␍
current_stage: 'layout_parsing',␍
lock_version: 1,␍
current_run_no: 'RUN-1',␍
...patch,␍
};␍
}␍
␍
type DocumentObject = ConversationProcessingObject & {␍
available_actions?: string[];␍
reparse_kind?: string | null;␍
lock_version?: number;␍
};␍
␍
/**␍
* 将 buildItem 文档行映射为 OT document object(供 processingFromDocuments 使用)。␍
*/␍
function documentObjectFromItem(doc: ShippingWorkflowItem): DocumentObject {␍
return {␍
kind: 'document',␍
object_key: doc.item_no,␍
workflow_item_no: doc.item_no,␍
label: String(doc.current_document_filename || doc.item_no),␍
filename: doc.current_document_filename ?? null,␍
status_label: doc.lifecycle_status,␍
document_id: doc.current_document_id,␍
root_document_id: doc.root_document_id,␍
content_hash: doc.content_hash ?? null,␍
current_run_no: doc.current_run_no ?? null,␍
case_no: doc.current_case_no ?? null,␍
available_actions: doc.available_actions,␍
reparse_kind: doc.reparse_kind ?? null,␍
lock_version: doc.lock_version,␍
};␍
}␍
␍
/**␍
* 构造含单个 processing 任务与 document objects 的会话投影。␍
* 核心逻辑:objects 默认由 docs 映射;taskOverrides 可覆盖任务卡字段或整组 objects。␍
*/␍
function processingFromDocuments(␍
docs: ShippingWorkflowItem[],␍
taskOverrides?: Partial<ConversationProcessingUserTask>,␍
): ConversationProcessingProjection {␍
const userTaskNo = taskOverrides?.user_task_no ?? DEFAULT_TASK_NO;␍
const objects = taskOverrides?.objects ?? docs.map(documentObjectFromItem);␍
const filenames = docs␍
.map((doc) => String(doc.current_document_filename || '').trim())␍
.filter(Boolean);␍
const task: ConversationProcessingUserTask = {␍
user_task_no: userTaskNo,␍
group: 'processing',␍
status_label: docs[0]?.lifecycle_status ?? 'extracting',␍
title: docs.length === 1 ? (docs[0]?.current_document_filename ?? null) : null,␍
display_kind: docs.length > 1 ? 'multi_document_task' : 'single_document_task',␍
document_names: filenames.length ? filenames : null,␍
file_count: docs.length,␍
run_no: docs[0]?.current_run_no ?? null,␍
can_append: false,␍
objects,␍
...taskOverrides,␍
};␍
␍
return {␍
summary: {␍
total_tasks: 1,␍
total_files: docs.length,␍
processing: 1,␍
needs_action: 0,␍
completed: 0,␍
history: 0,␍
},␍
focused_task_no: null,␍
recent_task_no: null,␍
needs_action: [],␍
processing: [task],␍
completed: [],␍
history: [],␍
};␍
}␍
␍
function buildController(␍
extras?: {␍
processing?: UseShippingNoticeWorkflowReturn['processing']['value'];␍
},␍
): UseShippingNoticeWorkflowReturn {␍
return {␍
processing: ref(extras?.processing ?? null),␍
processingWorkItems: ref([]),␍
loading: ref(false),␍
error: ref(null),␍
refresh: vi.fn(async () => undefined),␍
focusConversationTask: vi.fn(async () => undefined),␍
markConversationTaskViewed: vi.fn(async () => undefined),␍
stop: vi.fn(),␍
};␍
}␍
␍
/**␍
* 展开 processing 任务卡,使文件明细抽屉可见。␍
*/␍
async function expandProcessingTask(␍
wrapper: ReturnType<typeof mount>,␍
taskNo = DEFAULT_TASK_NO,␍
) {␍
if (wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()) {␍
return;␍
}␍
const task = wrapper.find(`[data-testid="shipping-processing-task-${taskNo}"]`);␍
expect(task.exists()).toBe(true);␍
await task.findAll('button').at(-1)!.trigger('click');␍
await flushPromises();␍
}␍
␍
async function openDetailsDrawer(␍
wrapper: ReturnType<typeof mount>,␍
taskNo = DEFAULT_TASK_NO,␍
) {␍
await flushPromises();␍
await expandProcessingTask(wrapper, taskNo);␍
expect(wrapper.find('[data-testid="shipping-workflow-details-drawer"]').exists()).toBe(true);␍
}␍
␍
const mountOptions = {␍
global: {␍
plugins: [i18n],␍
stubs: {␍
teleport: true,␍
},␍
},␍
};␍
␍
describe('ShippingWorkflowTimeline', () => {␍
beforeEach(() => {␍
document.body.innerHTML = '';␍
routerPush.mockClear();␍
});␍
␍
it('shows layout_parsing items with filename before review case exists', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-LAYOUT',␍
lifecycle_status: 'layout_parsing',␍
current_case_no: null,␍
current_document_filename: 'layout.pdf',␍
}),␍
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:layout 文件行展示文件名␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');␍
// 断言:无复核单时展示占位文案␍
expect(wrapper.text()).toContain('尚无复核单');␍
// 断言:有 OT 任务投影时隐藏独立「当前阶段」卡(UI-F04)␍
expect(wrapper.find('[data-testid="shipping-workflow-current-stage"]').exists()).toBe(false);␍
// 断言:processing / pending_review 分组均可见␍
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);␍
});␍
␍
it('shows processing and pending-review files together by default', async () => {␍
const processing = processingFromDocuments([␍
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),␍
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:默认同时展示处理中与待复核文件␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(true);␍
});␍
␍
it('opens the review workspace directly for pending review items', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-REVIEW-OPEN',␍
lifecycle_status: 'pending_review',␍
current_run_no: 'RUN-REVIEW-1',␍
current_case_no: 'CASE-REVIEW-1',␍
current_document_id: 42,␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
await wrapper.find('[data-testid="shipping-workflow-action-open-review"]').trigger('click');␍
// 断言:跳转 order-review 并携带 run / case / document 上下文␍
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({␍
name: 'Chat',␍
params: { agentId: 'agent-1' },␍
query: expect.objectContaining({␍
mode: 'order-review',␍
run_no: 'RUN-REVIEW-1',␍
case_no: 'CASE-REVIEW-1',␍
document_id: '42',␍
focus: 'draft',␍
}),␍
}));␍
});␍
␍
it('cancels an item via Run API from in-app reason dialog', async () => {␍
api.cancelRun.mockClear();␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-CANCEL',␍
lifecycle_status: 'extracting',␍
lock_version: 3,␍
current_run_no: 'RUN-CANCEL',␍
available_actions: ['cancel'],␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');␍
await flushPromises();␍
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');␍
// 断言:应用内原因弹窗出现␍
expect(reasonInput.exists()).toBe(true);␍
await reasonInput.setValue('cancel reason');␍
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');␍
await flushPromises();␍
// 断言:调用 Run 取消 API␍
expect(api.cancelRun).toHaveBeenCalledWith('RUN-CANCEL', { reason: 'cancel reason' });␍
});␍
␍
it('hides WF batch switcher as primary path', async () => {␍
const processing = processingFromDocuments([buildItem({ item_no: 'SWI-A' })]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: {␍
conversationId: 'conv-1',␍
controller: buildController({ processing }),␍
},␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:批次切换器不再作为主路径展示␍
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(false);␍
});␍
␍
it('shows reparse action for failed items', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-FAIL',␍
lifecycle_status: 'failed',␍
current_document_filename: 'bad.pdf',␍
current_run_no: 'RUN-FAIL',␍
available_actions: ['cancel', 'reparse'],␍
reparse_kind: 'failed_run_retry',␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:失败项展示重识别按钮与文案␍
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);␍
expect(wrapper.text()).toContain('重试失败识别');␍
});␍
␍
it('hides reparse for pending_review without available_actions.reparse', async () => {␍
const processing = processingFromDocuments([␍
buildItem({␍
item_no: 'SWI-PR',␍
lifecycle_status: 'pending_review',␍
current_case_no: null,␍
available_actions: ['cancel'],␍
reparse_kind: null,␍
}),␍
]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
// 断言:无 reparse 契约时不展示重识别␍
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(false);␍
});␍
␍
it('keeps sidebar width while showing inline workflow details', async () => {␍
const processing = processingFromDocuments([buildItem()]);␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: {␍
conversationId: 'conv-1',␍
controller: buildController({ processing }),␍
},␍
...mountOptions,␍
});␍
await openDetailsDrawer(wrapper);␍
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
// 断言:侧栏宽度不变␍
expect(aside.classes().join(' ')).toContain('md:w-[clamp(20rem,28vw,30rem)]');␍
const overlay = wrapper.find('[data-testid="shipping-workflow-details-drawer"]');␍
// 断言:文件明细内联展示,非 modal␍
expect(overlay.exists()).toBe(true);␍
expect(overlay.classes().join(' ')).toContain('rounded-xl');␍
expect(overlay.find('[role="dialog"]').exists()).toBe(false);␍
});␍
␍
it('keeps panel expanded while processing tasks exist', async () => {␍
const processing = processingFromDocuments([buildItem()], {␍
user_task_no: 'OT-PIN',␍
status_label: 'extracting',␍
title: 'order.pdf',␍
file_count: 1,␍
run_no: 'RUN-PIN',␍
});␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await flushPromises();␍
const aside = wrapper.find('[data-testid="shipping-workflow-timeline"]');␍
const toggle = wrapper.find('[data-testid="shipping-workflow-panel-toggle"]');␍
// 断言:有 processing 任务时侧栏默认展开␍
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
await toggle.trigger('click');␍
await flushPromises();␍
// 断言:点击收起仍保持展开(pinned)␍
expect(aside.classes().join(' ')).not.toContain('!w-14');␍
expect(wrapper.find('[data-testid="shipping-processing-task-OT-PIN"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-panel-pinned"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-panel-summary"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-processing-summary"]').exists()).toBe(false);␍
});␍
␍
it('expands all effective PDFs for one task even when they belong to different runs', async () => {␍
const docs = [␍
buildItem({␍
item_no: 'SWI-PDF-91',␍
current_run_no: 'RUN-NEW',␍
root_document_id: 91,␍
current_document_id: 191,␍
content_hash: 'hash-a',␍
current_document_filename: '4518838152.pdf',␍
}),␍
buildItem({␍
item_no: 'SWI-PDF-92',␍
current_run_no: 'RUN-OLD',␍
root_document_id: 92,␍
current_document_id: 92,␍
content_hash: 'hash-b',␍
current_document_filename: '4518838154.pdf',␍
}),␍
];␍
const processing = processingFromDocuments(docs, {␍
user_task_no: 'OT-MULTI-RUN',␍
status_label: 'extracting',␍
title: null,␍
display_kind: 'multi_document_task',␍
document_names: ['4518838152.pdf', '4518838154.pdf'],␍
file_count: 2,␍
run_no: 'RUN-NEW',␍
objects: [␍
{␍
kind: 'document', object_key: 'DOC-191', workflow_item_no: 'SWI-PDF-91', label: '4518838152.pdf',␍
status_label: 'extracting', document_id: 191, root_document_id: 91,␍
content_hash: 'hash-a', current_run_no: 'RUN-NEW',␍
},␍
{␍
kind: 'document', object_key: 'DOC-92', workflow_item_no: 'SWI-PDF-92', label: '4518838154.pdf',␍
status_label: 'pending_review', document_id: 92, root_document_id: 92,␍
content_hash: 'hash-b', current_run_no: 'RUN-OLD',␍
},␍
],␍
});␍
const wrapper = mount(ShippingWorkflowTimeline, {␍
props: { conversationId: 'conv-1', controller: buildController({ processing }) },␍
...mountOptions,␍
});␍
await flushPromises();␍
␍
const task = wrapper.find('[data-testid="shipping-processing-task-OT-MULTI-RUN"]');␍
expect(task.exists()).toBe(true);␍
await task.findAll('button').at(-1)!.trigger('click');␍
await flushPromises();␍
␍
// 断言:任务内两 PDF 均展示,无关 PDF 被过滤␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-91"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-PDF-92"]').exists()).toBe(true);␍
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-OTHER"]').exists()).toBe(false);␍
});␍
});␍
File diff suppressed because it is too large. Load diff
@@ -629,6 +629,8 @@ export function useChatPage() {
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
getActiveOrderExtractionRunNo: shipping.getActiveOrderExtractionRunNo,
workflowRefreshTrigger: shipping.workflowRefreshTrigger,
focusedConversationTaskNo: shipping.focusedConversationTaskNo,
setFocusedConversationTaskNo: shipping.setFocusedConversationTaskNo,
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
switchShippingBatch: shipping.switchShippingBatch,
@@ -13,6 +13,7 @@ const { deleteAllChatSessions, deleteChatSession, listChatSessions } = vi.hoiste
deleteChatSession: vi.fn(),
listChatSessions: vi.fn(),
}));
const listWorkspaceShippingOrderExtractionRuns = vi.hoisted(() => vi.fn());
const {
getSessionHistory,
@@ -29,6 +30,7 @@ vi.mock('../api/chat.api', () => ({
deleteChatSession,
listChatSessions,
}));
vi.mock('../api/shipping.api', () => ({ listWorkspaceShippingOrderExtractionRuns }));
vi.mock('../stores/chat.store', () => ({
useChatStore: () => ({
@@ -43,6 +45,7 @@ describe('useChatSessions', () => {
deleteAllChatSessions.mockReset();
deleteChatSession.mockReset();
listChatSessions.mockReset();
listWorkspaceShippingOrderExtractionRuns.mockReset();
getSessionHistory.mockReset();
setSessionHistory.mockReset();
patchSessionHistory.mockReset();
@@ -91,4 +94,41 @@ describe('useChatSessions', () => {
expect(runs.value).toEqual([]);
expect(startNewChat).toHaveBeenCalledTimes(1);
});
it('rebuilds order-review query from the selected conversation', async () => {
const replace = vi.fn();
listWorkspaceShippingOrderExtractionRuns.mockResolvedValue({
items: [{ run_no: 'RUN-NEW', status: 'review_required' }],
});
const sessions = useChatSessions({
deps: {
t: (key: string) => key,
router: { replace },
route: {
path: '/chat/7',
query: {
conversation_id: 'conv-old', mode: 'order-review', run_no: 'RUN-OLD',
case_no: 'CASE-OLD', document_id: '91', focus: 'evidence',
},
},
} as never,
currentAgentId: computed(() => 7),
conversationId: ref('conv-old'),
activeRunId: ref(null),
runs: ref([]),
activateRun: vi.fn(),
loadConversation: vi.fn(async () => {}),
isSidebarOpen: ref(true),
onConfirmDelete: vi.fn(),
startNewChat: vi.fn(),
});
await sessions.handleHistorySelect({ id: 2, conversation_id: 'conv-new' } as never);
expect(listWorkspaceShippingOrderExtractionRuns).toHaveBeenCalledWith('conv-new', 20);
expect(replace).toHaveBeenCalledWith({
path: '/chat/7',
query: { conversation_id: 'conv-new', mode: 'order-review', run_no: 'RUN-NEW' },
});
});
});
@@ -8,6 +8,7 @@ import {
deleteChatSession,
listChatSessions,
} from '../api/chat.api';
import { listWorkspaceShippingOrderExtractionRuns } from '../api/shipping.api';
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
import type { ChatDeps } from './chat.deps';
import { useChatStore } from '../stores/chat.store';
@@ -133,6 +134,22 @@ export function useChatSessions(options: UseChatSessionsOptions) {
return;
}
const isOrderReview = route.query.mode === 'order-review';
if (isOrderReview) {
// 复核工作台的 Run/Case/文档上下文属于旧会话,切换时必须整体重建,不能只替换 conversation_id。
const restored = await listWorkspaceShippingOrderExtractionRuns(item.conversation_id, 20);
const nextRun = (restored.items || []).find((candidate) =>
['review_required', 'partially_completed'].includes(String(candidate.status || '')),
);
const nextQuery: Record<string, string> = { conversation_id: item.conversation_id };
if (nextRun?.run_no) {
nextQuery.mode = 'order-review';
nextQuery.run_no = String(nextRun.run_no);
}
await router.replace({ path: route.path, query: nextQuery });
return;
}
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;
delete nextQuery.preset;
@@ -1,9 +1,11 @@
/**
* features/chat/composables/useChatShipping.ts
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
* 依赖:shipping.api(任务/客户等)、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件维护会话任务摘要 + ui_state 同步,
* 不再管理批次抽屉/焦点条/聊天履约写按钮(履约写改由任务处理工作台承接)。
* 以及 focusedConversationTaskNo(提交追加优先级 / 侧栏焦点);
* co8:shipping_batches 工作台轮询已下线,进度改由 shipping-processing projection 承接;
* 保留 resolvedShippingBatchNo / shippingBatchSummary 等 ref 供调用方兼容,不再发起批次网络请求。
*/
import {
@@ -38,18 +40,18 @@ import {
import { isShippingSpreadsheetFile } from '../shipping/shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
listWorkspaceShippingCustomerOptions,
confirmWorkspaceShippingCustomer,
type ShippingBatchUiState,
type ShippingBatchSummary,
type ShippingConversationWorkspace,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import type { ShippingCustomerOption } from '../types/shipping.api.types';
import type {
ShippingBatchSummary,
ShippingBatchUiState,
ShippingCustomerOption,
} from '../types/shipping.api.types';
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
import {
hasShortageLines,
@@ -346,6 +348,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
};
/**
* 同步批次摘要占位(co8 已下线批次详情 API)。
*
* 核心逻辑:batchNo 为空时清空摘要;否则仅回填本地 batch_no 与已有 task 焦点,不发起网络请求。
* @param batchNo - 目标批次号
*/
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
if (!normalized) {
@@ -353,52 +361,32 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingBatchTasks.value = [];
return;
}
try {
const detail = await getWorkspaceShippingBatch(normalized);
applyShippingBatchDetail(detail, normalized);
} catch {
// ignore summary refresh failure in chat flow
resolvedShippingBatchNo.value = normalized;
if (!activeShippingBatchNo.value) {
activeShippingBatchNo.value = normalized;
}
shippingBatchSummary.value = {
id: 0,
batch_no: normalized,
conversation_id: conversationId.value,
current_focus_task_no: resolvedShippingTaskId.value || null,
process_summary: null,
};
};
const applyConversationWorkspaceFocus = (
workspace: ShippingConversationWorkspace,
options?: { preferLatest?: boolean },
) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = selectShippingConversationBatch(
batches,
currentBatchNo,
queryBatchNo,
Boolean(options?.preferLatest),
);
if (!selectedBatch) return;
if (options?.preferLatest) {
activeShippingBatchNo.value = selectedBatch.batch_no;
}
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
/**
* 同步会话批次工作台(co8 已下线 conversation batches API)。
*
* 核心逻辑:保留调用签名供抽取 Run / 终态刷新链路兼容;始终清空 workspace 并返回 false,不发起网络。
* @param _options - 历史参数,保留兼容
* @returns 恒为 false
*/
const syncShippingConversationWorkspace = async (
options?: { preferLatest?: boolean },
_options?: { preferLatest?: boolean },
): Promise<boolean> => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return false;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace, options);
return true;
} catch {
shippingConversationWorkspace.value = null;
return false;
}
void _options;
shippingConversationWorkspace.value = null;
return false;
};
/**
@@ -469,13 +457,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
recovered = true;
}
if (!snapshot && batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and continue with task-first recovery
}
await syncShippingBatchSummary(batchNo);
recovered = true;
}
if (taskNo) {
await syncActiveShippingTaskDetail(taskNo);
@@ -486,13 +469,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
activeShippingBatchNo.value = detailBatchNo;
}
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
try {
const detail = await getWorkspaceShippingBatch(batchNo);
applyShippingBatchDetail(detail, batchNo);
recovered = true;
} catch {
// ignore and keep task-only recovery
}
await syncShippingBatchSummary(batchNo);
recovered = true;
}
recovered = recovered || Boolean(activeShippingTaskDetail.value);
}
@@ -504,33 +482,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
);
/**
* 切换会话上传摘要中的活动批次(只读同步,无焦点条/抽屉写操作)。
* 切换会话上传摘要中的活动批次(co8 已下线,保留签名兼容)。
*
* 核心逻辑:批次工作台 API 已移除,调用时仅提示用户改由右侧 processing 工作台操作。
* @param batchNo - 目标批次号
* @returns 是否切换成功
* @returns 恒为 false
*/
const switchShippingBatch = async (batchNo: string) => {
const normalizedBatchNo = String(batchNo || '').trim();
if (!normalizedBatchNo) return false;
activeShippingBatchNo.value = normalizedBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
const workspaceBatch = shippingConversationWorkspace.value?.batches.find((item) => item.batch_no === normalizedBatchNo);
if (workspaceBatch) {
applyShippingBatchDetail(workspaceBatch, normalizedBatchNo);
} else {
await syncShippingBatchSummary(normalizedBatchNo);
}
const nextFocusState = resolveShippingBatchFocusState(
shippingBatchSummary.value,
shippingBatchTasks.value,
'',
);
const nextTaskNo = nextFocusState.taskNo;
if (nextTaskNo) {
resolvedShippingTaskId.value = nextTaskNo;
await syncActiveShippingTaskDetail(nextTaskNo);
}
await refreshShippingActions();
return true;
msg.warning(t('chat.shippingNoticeUi.batchSwitchRemoved'));
return false;
};
/**
@@ -540,6 +502,9 @@ export function useChatShipping(options: UseChatShippingOptions) {
* 避免会话摘要和待上传库存文件残留到下一次新会话。
*/
const resetShippingConversationState = () => {
// 新对话不会触发 onConversationIdChanging;必须在此清掉旧 Run,
// 否则右侧面板仍会将其作为当前会话的展示条件。
shippingOrderExtractionRuns.clearActiveRun();
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingNoticeTaskId.value = '';
@@ -796,6 +761,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
const bumpWorkflowRefresh = () => {
workflowRefreshTrigger.value += 1;
};
/** 侧栏/提交共用的当前聚焦用户可见任务(OT-…)。 */
const focusedConversationTaskNo = ref<string | null>(null);
const setFocusedConversationTaskNo = (taskNo: string | null) => {
focusedConversationTaskNo.value = String(taskNo || '').trim() || null;
};
const shippingOrderExtractionRuns = useShippingOrderExtractionRuns({
messages,
conversationId,
@@ -818,6 +788,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
},
onRetryError: (message) => msg.error(message),
onWorkflowRefresh: bumpWorkflowRefresh,
getFocusedUserTaskNo: () => focusedConversationTaskNo.value,
setFocusedUserTaskNo: setFocusedConversationTaskNo,
t,
});
@@ -1024,6 +996,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
enqueueNoticeFiles: shippingIntakes.enqueueNoticeFiles,
startOrderExtractionRun: (...args) => shippingOrderExtractionRuns.startRun(...args),
sendTemporaryInventoryMessage: async (assetNo, fileName) => sendMessage(
`我已上传库存文件:${fileName},请先检查文件结构并说明下一步。`,
currentAgentId.value,
@@ -1147,6 +1121,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
onNoticeBatchConversationChanging(nextId, prevId);
shippingIntakes.stopPolling();
if (nextId && nextId !== prevId) {
focusedConversationTaskNo.value = null;
void shippingIntakes.restoreForConversation(nextId);
void shippingOrderExtractionRuns.restoreForConversation(nextId);
} else {
@@ -1163,33 +1138,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
/**
* 重试当前聚焦批次中可恢复的失败/排队任务(供页面级确认弹窗调用;Chat 本身不再挂批次抽屉按钮)。
* @returns 成功时返回 started/skipped;失败或跳过时返回 null
* 重试当前聚焦批次中可恢复的失败/排队任务(co8 已下线,保留签名兼容)。
*
* 核心逻辑:批次重试 API 已移除,调用时提示用户改由 processing 工作台或任务动作重试。
* @returns 恒为 null
*/
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
started: number;
skipped: number;
} | null> => {
const batchNo = getActiveShippingBatchNo();
if (!batchNo) return null;
if (isShippingActionBusy.value) {
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
return null;
}
try {
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
const result = await retryWorkspaceShippingBatchPending(batchNo);
await syncShippingConversationWorkspace();
await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return {
started: Number(result.started ?? 0),
skipped: Number(result.skipped ?? 0),
};
} catch (error) {
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
return null;
}
msg.warning(t('chat.shippingNoticeUi.batchRetryRemoved'));
return null;
};
const handleShippingLocalFilesSelected = (event: Event): boolean => {
@@ -1247,8 +1206,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
/**
* 启停发货会话状态短轮询。
*
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
* 让右侧会话摘要与通知态 ui_state 能在后端异步状态变化后自动更新。
* 核心逻辑:co8 后不再轮询 shipping_batches;仅在存在任务上下文时每 3 秒补拉任务详情与动作按钮,
* 批次/处理进度改由 shipping-processing projection 承接。
*/
const restartShippingStatusPolling = () => {
if (shippingStatusPollTimer) {
@@ -1256,22 +1215,16 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingStatusPollTimer = null;
}
if (!isShippingNoticeAgent.value) return;
const batchNo = getActiveShippingBatchNo();
const taskId = getActiveBatchTaskId();
if (!batchNo && !taskId) return;
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
if (!taskId) return;
shippingStatusPollTimer = setInterval(() => {
if (!isShippingNoticeAgent.value) return;
const nextBatchNo = getActiveShippingBatchNo();
const nextTaskId = getActiveBatchTaskId();
if (!nextBatchNo && !nextTaskId) return;
const nextTaskId = getActiveBatchTaskId() || getActiveShippingTaskId();
if (!nextTaskId) return;
void (async () => {
await syncShippingConversationWorkspace();
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
if (nextTaskId) {
await syncActiveShippingTaskDetail(nextTaskId);
await syncConversationMessagesIfNeeded(nextTaskId);
}
await syncActiveShippingTaskDetail(nextTaskId);
await syncConversationMessagesIfNeeded(nextTaskId);
await refreshShippingActions();
if (!hasRunningShippingBatchTasks() && !isShippingActionBusy.value && shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
@@ -1395,6 +1348,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
reparseOrderExtractionRun: shippingOrderExtractionRuns.reparseRun,
getActiveOrderExtractionRunNo: shippingOrderExtractionRuns.getActiveRunNo,
workflowRefreshTrigger,
focusedConversationTaskNo,
setFocusedConversationTaskNo,
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
setShippingCandidateSelected,
resolveShippingCandidateDuplicate,
@@ -1404,6 +1359,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
showShippingCustomerDialog,
shippingCustomerOptions,
shippingCustomerLoading,
openShippingCustomerDialog,
searchShippingCustomers,
confirmShippingCustomer,
closeShippingCustomerDialog: () => {
@@ -0,0 +1,87 @@
/**
* features/chat/e2e/shipping-conversation-multiple-runs.spec.ts
* 用途:会话多任务聚合阶段 3–5 契约冒烟——发送无确认框、任务分组主路径、WF 非主标题。
* 依赖:Vitest、conversationProcessingProjection、shippingSubmissionFeedback。
* 逻辑:不启浏览器;用投影/反馈纯函数断言产品契约,避免 e2e 环境依赖。
*/
import { describe, expect, it } from 'vitest';
import {
classifyConversationProcessingGroup,
groupConversationProcessingTasks,
projectConversationProcessingTasks,
} from '@/features/chat/shipping/conversationProcessingProjection';
import { buildShippingSubmissionFeedback } from '@/features/chat/shipping/shippingSubmissionFeedback';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
item_no: 'WI-1',
workflow_no: 'WF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
lifecycle_status: 'queued',
current_stage: 'queued',
lock_version: 1,
...partial,
};
}
describe('shipping conversation multiple runs e2e contract', () => {
it('maps backend decisions to non-blocking feedback without dialog keys', () => {
const appended = buildShippingSubmissionFeedback({
decision: 'appended',
user_task_no: 'OT-1',
run_no: 'RUN-1',
created_new: false,
}, 2);
const created = buildShippingSubmissionFeedback({
decision: 'created',
user_task_no: 'OT-2',
run_no: 'RUN-2',
created_new: true,
}, 1);
// 关键断言:仅两种决策;短时标签供右侧卡,不依赖确认弹窗。
expect(appended.decision).toBe('appended');
expect(created.decision).toBe('created');
expect([appended.badgeCode, created.badgeCode]).toEqual(['just_appended', 'just_created']);
});
it('keeps WF/run ids as secondary while grouping by user-visible tasks', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
workflow_no: 'WF-AAA',
current_run_no: 'SNER-A',
lifecycle_status: 'pending_review',
}),
item({
item_no: 'WI-B',
workflow_no: 'WF-BBB',
current_run_no: 'SNER-B',
lifecycle_status: 'extracting',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
expect(projection.summary.total_tasks).toBe(2);
expect(projection.needs_action).toHaveLength(1);
expect(projection.processing).toHaveLength(1);
// 关键断言:主对象是 OT-;WF 仅挂在任务上供诊断。
expect(projection.needs_action[0]?.user_task_no.startsWith('OT-')).toBe(true);
expect(projection.needs_action[0]?.workflow_no).toBe('WF-AAA');
expect(classifyConversationProcessingGroup('failed')).toBe('needs_action');
});
it('scales to twenty user-visible tasks without inventing progress percent', () => {
const items = Array.from({ length: 20 }, (_, index) => item({
item_no: `WI-${index}`,
current_run_no: `SNER-${index}`,
lifecycle_status: index % 2 === 0 ? 'extracting' : 'closed',
}));
const projection = groupConversationProcessingTasks(projectConversationProcessingTasks(items));
expect(projection.summary.total_tasks).toBe(20);
expect(projection.summary.processing + projection.summary.history).toBe(20);
expect(JSON.stringify(projection).includes('percent')).toBe(false);
});
});
@@ -1,8 +1,8 @@
/**
* features/chat/page/useChatPageConversation.spec.ts
* 用途:验证新建聊天与 Agent 切换时清理发货通知待重试建批幂等状态。
* 用途:验证新建聊天与 Agent 切换时清理发货通知外围状态。
* 依赖:vitest、vue refs/computed、useChatPageConversation、useChatShippingUploadHandler。
* 逻辑:覆盖 createNewChatView 不经 onConversationIdChanging 时仍生成新幂等键的回归场景。
* 逻辑:覆盖 createNewChatView / Agent 切换调用 peripheral reset;建批幂等已随 co8 下线。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -18,21 +18,10 @@ const { listChatMessages } = vi.hoisted(() => ({
listChatMessages: vi.fn(),
}));
const { computeNoticeFilesContentFingerprint } = vi.hoisted(() => ({
computeNoticeFilesContentFingerprint: vi.fn(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
}),
}));
vi.mock('../api/chat.api', () => ({
listChatMessages,
}));
vi.mock('../shipping/shippingNoticeBatchIdempotency', () => ({
computeNoticeFilesContentFingerprint,
}));
const createConversationContext = () => {
const conversationId = ref<string | null>('conv-a');
const messages = ref([]);
@@ -41,6 +30,7 @@ const createConversationContext = () => {
messages.value = [];
});
const resetPeripheralState = vi.fn();
return {
conversationId,
messages,
@@ -68,18 +58,19 @@ const createConversationContext = () => {
input: ref(''),
resetCurrentAgent: vi.fn(),
copiedIndex: ref(null),
resetPeripheralState: vi.fn(),
resetPeripheralState,
filePreviewVisible: ref(false),
previewFile: ref(null),
previewFiles: ref([]),
currentPreviewIndex: ref(0),
}),
resetPeripheralState,
};
};
const createUploadContext = (
conversationId: ReturnType<typeof ref<string | null>>,
startChatTurn: ReturnType<typeof vi.fn>,
enqueueNoticeFiles: ReturnType<typeof vi.fn>,
): ShippingUploadHandlerContext => ({
conversationId,
currentAgentId: computed(() => 42),
@@ -97,35 +88,32 @@ const createUploadContext = (
shippingBatchTasks: ref([]),
shippingInventorySelectionActive: ref(false),
shippingInventorySelectionTaskId: ref(''),
shippingInventorySchemaPreviewCache: ref({}),
getActiveShippingTaskId: () => '',
startChatTurn,
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
enqueueNoticeFiles,
startOrderExtractionRun: vi.fn(async () => true),
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
});
describe('useChatPageConversation', () => {
beforeEach(() => {
listChatMessages.mockReset();
computeNoticeFilesContentFingerprint.mockReset();
computeNoticeFilesContentFingerprint.mockImplementation(async (files: File[]) => {
const content = await files[0]?.text();
return `fp-${content || 'empty'}`;
});
resetShippingNoticeBatchSubmitStateForTests();
});
it('startNewChat clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
it('startNewChat clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
createUploadContext(conversationId, enqueueNoticeFiles),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
api.startNewChat();
@@ -133,23 +121,28 @@ describe('useChatPageConversation', () => {
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
});
it('resetChatStateForAgentChange clears pending notice batch retry and next upload uses a new idempotency key', async () => {
const startChatTurn = vi.fn(async () => false);
it('startNewChat calls peripheral reset so a shipping Run cannot remain visible in the blank view', () => {
const { api, resetPeripheralState } = createConversationContext();
api.startNewChat();
// 关键断言:Shipping 状态在 useChatShipping.resetShippingConversationState 中随该回调清理。
expect(resetPeripheralState).toHaveBeenCalledTimes(1);
});
it('resetChatStateForAgentChange clears peripheral state and subsequent notice upload still enqueues intakes', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const { conversationId, createNewChatView, api } = createConversationContext();
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(
createUploadContext(conversationId, startChatTurn),
createUploadContext(conversationId, enqueueNoticeFiles),
);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
api.resetChatStateForAgentChange();
@@ -157,10 +150,6 @@ describe('useChatPageConversation', () => {
expect(conversationId.value).toBeNull();
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(2);
});
});
@@ -47,4 +47,15 @@ describe('parseOrderReviewConfirmResponse', () => {
it('returns null without task_no', () => {
expect(parseOrderReviewConfirmResponse(baseResponse({ task_no: null }))).toBeNull();
});
it('prefers order_task_no for focus identity and keeps Notice as taskNo', () => {
const parsed = parseOrderReviewConfirmResponse(baseResponse({
task_no: 'SN-NOTICE',
shipping_notice_no: 'SN-NOTICE',
order_task_no: 'OT-ROOT-C102',
}));
// 关键断言:对话聚焦必须用 OT,不能把 Notice 编号当成 OT。
expect(parsed?.taskNo).toBe('SN-NOTICE');
expect(parsed?.orderTaskNo).toBe('OT-ROOT-C102');
});
});
@@ -2,7 +2,8 @@
* features/chat/shipping-review/parseOrderReviewConfirmResponse.ts
* 用途:统一解析复核确认建单 API 的业务态,禁止调用方仅凭 HTTP/success/confirm_ok 判定推进成功。
* 依赖:ShippingOrderReviewConfirmResponse 类型。
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐。
* 逻辑:ShippingOrderReviewView / 其他确认调用方共用;与后端 resolve_confirm_outcome 枚举对齐;
* 同时暴露 shipping_notice_no 与 order_task_no,禁止用 Notice 编号聚焦 OT 卡。
*/
import type { ShippingOrderReviewConfirmResponse } from '@/features/chat/types/shipping.api.types';
@@ -16,7 +17,10 @@ export type ShippingOrderReviewConfirmOutcome =
/** 确认响应解析结果:建单与自动推进解耦。 */
export interface ParsedOrderReviewConfirmResult {
/** 正式 ShippingNotice 编号(自动推进 / 工作台)。 */
taskNo: string;
/** Candidate 一对一 OT 编号(对话右侧聚焦)。 */
orderTaskNo: string;
confirmOk: boolean;
confirmOutcome: ShippingOrderReviewConfirmOutcome;
/** 自动推进已入队/启动 */
@@ -36,17 +40,26 @@ const PROGRESS_FAILED_STATUSES = new Set([
/**
* 解析复核确认响应的业务态。
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status。
* 核心逻辑:confirm_ok 仅表示建单成功;推进成败读 confirm_outcome / auto_progress.status;
* focus / 统一进度只认 order_task_no,task_no 仅表示 Notice。
*
* @param response - confirm API data(非 HTTP envelope)
* @returns 解析结果;无 task_no 时返回 null
* @returns 解析结果;无 Notice task_no 时返回 null
*/
export function parseOrderReviewConfirmResponse(
response: ShippingOrderReviewConfirmResponse | null | undefined,
): ParsedOrderReviewConfirmResult | null {
const taskNo = String(response?.task_no || '').trim();
const taskNo = String(
response?.shipping_notice_no || response?.task_no || '',
).trim();
if (!taskNo) return null;
const orderTaskNo = String(
response?.order_task_no
|| response?.case?.order_task_no
|| '',
).trim();
const progressStatus = String(response?.auto_progress?.status || '').trim();
const confirmOutcome = String(response?.confirm_outcome || '').trim()
|| (PROGRESS_FAILED_STATUSES.has(progressStatus)
@@ -63,6 +76,7 @@ export function parseOrderReviewConfirmResponse(
return {
taskNo,
orderTaskNo,
confirmOk: response?.confirm_ok !== false,
confirmOutcome,
autoProgressStarted,
@@ -0,0 +1,43 @@
/**
* features/chat/shipping-review/showReviewResumeOutcome.ts
* 用途:复核写操作后统一展示 resume_outcome 提示(与 Customer 面板一致)。
* 依赖:vue-i18n、ShippingOrderReviewResumeOutcome。
* 逻辑:各 Reservation / 冲突 / 重复 / 履约面板在 API 成功后调用本 helper。
*/
import type { ComposerTranslation } from 'vue-i18n';
import type { ShippingOrderReviewResumeOutcome } from '../types/shipping.api.types';
type ToastApi = {
success: (message: string) => void;
};
/**
* 按 resume_outcome 展示成功提示;无 outcome 时使用 fallbackSuccess。
* 核心逻辑:auto_created/idempotent_replay → 自动建单;waiting_manual_confirm → 待人工确认。
* @param resume - 后端统一恢复协调结果
* @param msg - useMessage 实例
* @param t - vue-i18n translate
* @param fallbackSuccess - 无特殊 outcome 时的默认成功文案
* @returns 是否已展示 resume 专用提示(调用方可跳过 fallback)
*/
export function showReviewResumeOutcome(
resume: ShippingOrderReviewResumeOutcome | null | undefined,
msg: ToastApi,
t: ComposerTranslation,
fallbackSuccess?: string,
): void {
const outcome = String(resume?.outcome || '').trim();
if (outcome === 'auto_created' || outcome === 'idempotent_replay') {
msg.success(t('chat.shippingOrderReview.resume.autoCreated', {
taskNo: resume?.task_no || '',
}));
return;
}
if (outcome === 'waiting_manual_confirm') {
msg.success(t('chat.shippingOrderReview.resume.waitingManualConfirm'));
return;
}
if (fallbackSuccess) {
msg.success(fallbackSuccess);
}
}
@@ -54,8 +54,8 @@ const api = vi.hoisted(() => ({
getPreview: vi.fn(),
listWorkflows: vi.fn(),
getWorkflowItem: vi.fn(),
getExtractionRun: vi.fn(),
getProcessingWorkItem: vi.fn(),
reparseDocument: vi.fn(),
@@ -80,9 +80,8 @@ vi.mock('../api/shipping.api', () => ({
getWorkspaceShippingOrderReviewPreview: api.getPreview,
listWorkspaceShippingWorkflows: api.listWorkflows,
getWorkspaceShippingWorkflowItem: api.getWorkflowItem,
getWorkspaceShippingOrderExtractionRun: api.getExtractionRun,
getWorkspaceShippingProcessingWorkItem: api.getProcessingWorkItem,
putWorkspaceShippingOrderReviewInventoryCandidates: api.putInventoryCandidates,
postWorkspaceShippingOrderReviewInventoryRoutingReroute: api.rerouteInventoryRouting,
@@ -224,17 +223,12 @@ describe('useShippingOrderReview historical readonly', () => {
it('forces readonly when session work item is closed', () => {
expect(isReviewWorkItemClosed({ lifecycle_status: 'closed', current_case_no: 'CASE-1' })).toBe(true);
expect(isReviewWorkItemClosed({ lifecycle_status: 'manual_upload_pending', current_case_no: 'CASE-1' })).toBe(false);
expect(isReviewReadOnly(
{ case_no: 'CASE-1', status: 'draft' },
{ current_case_no: 'CASE-1', lifecycle_status: 'closed' },
)).toBe(true);
});
});
@@ -377,20 +371,9 @@ describe('useShippingOrderReview build eligibility writes', () => {
api.getPreview.mockRejectedValue(new Error('preview unavailable'));
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
api.getWorkflowItem.mockResolvedValue({
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
current_case_no: 'CASE-1',
lifecycle_status: 'pending_review',
current_stage: 'pending_review',
lock_version: 1,
});
api.getProcessingWorkItem.mockRejectedValue(
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
);
api.getCase.mockResolvedValue(buildCase());
@@ -559,21 +542,23 @@ describe('useShippingOrderReview build eligibility writes', () => {
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue({ preview_url: '' });
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
api.getWorkflowItem.mockResolvedValue({
item_no: 'WFI-1',
workflow_no: 'WF-1',
lifecycle_status: 'building_order',
current_stage: 'building_order',
current_task_no: 'SN-1',
current_version_no: 1,
api.getProcessingWorkItem.mockResolvedValueOnce({
work_item_no: 'OT-1',
status: 'building_order',
});
api.getProcessingWorkItem.mockResolvedValueOnce({
work_item_no: 'OT-1',
status: 'completed',
});
api.confirmCase.mockResolvedValue({
task_no: 'SN-1',
order_task_no: 'OT-1',
shipping_notice_no: 'SN-1',
idempotent_replay: false,
workflow_id: 'WF-1',
workflow_item_id: 'WFI-1',
case: { ...readyCase, status: 'confirmed' },
order_task_no: 'OT-1',
shipping_notice_no: 'SN-1',
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' },
auto_progress_started: true,
});
@@ -581,56 +566,104 @@ describe('useShippingOrderReview build eligibility writes', () => {
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
const response = await review.confirm();
expect(response?.workflow_item_id).toBe('WFI-1');
expect(response?.order_task_no).toBe('OT-1');
expect(response?.shipping_notice_no || response?.task_no).toBeTruthy();
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-1');
expect(review.showWorkflowProgress.value).toBe(true);
expect(review.workflowProgressPolling.value).toBe(true);
expect(api.getWorkflowItem).toHaveBeenCalled();
expect(api.getProcessingWorkItem).toHaveBeenCalled();
api.getWorkflowItem.mockResolvedValue({
item_no: 'WFI-1',
workflow_no: 'WF-1',
lifecycle_status: 'manual_upload_pending',
current_stage: 'manual_upload_pending',
current_task_no: 'SN-1',
current_version_no: 1,
});
await vi.advanceTimersByTimeAsync(2600);
expect(review.workItem.value?.lifecycle_status).toBe('manual_upload_pending');
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
vi.useRealTimers();
});
it('does not fall back to extraction run root OT when case has candidate binding', async () => {
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
order_task_no: 'OT-CAND',
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'draft', available_actions: ['edit_draft'] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
expect(review.reviewProgressContext.value?.user_task_no).toBe('OT-CAND');
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(true);
});
it('leaves OT unset during reparse polling when candidate-bound case lacks order_task_no', async () => {
vi.useFakeTimers();
api.getCase.mockResolvedValue(buildCase({
candidate_id: 42,
candidate: { candidate_no: 'CAND-42', validation_status: 'ready' },
}));
api.getRun.mockResolvedValue({
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', document_id: 1, status: 'reparse_pending', available_actions: [] }],
});
api.getEvidence.mockResolvedValue({ items: [] });
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-2' },
reused: false,
});
api.getExtractionRun.mockResolvedValue({
run_no: 'RUN-2',
status: 'extracting',
user_task_no: 'OT-ROOT',
current_activity: { user_visible_stage: 'extracting' },
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1' });
await review.reparseDocument('layout_issue');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(review.reviewProgressContext.value?.user_task_no).toBeNull();
expect(review.reviewProgressContext.value?.user_task_authoritative).toBe(false);
review.stopReparseProgressPolling();
vi.useRealTimers();
});
it('polls reparse progress and loads the new review version when ready', async () => {
vi.useFakeTimers();
let reparseStarted = false;
let reparsePollCount = 0;
api.reparseDocument.mockImplementation(async () => {
reparseStarted = true;
return { run: { run_no: 'RUN-2', items: [], summary: {} }, reused: false };
});
api.reparseDocument.mockImplementation(async () => ({
run: { run_no: 'RUN-2', items: [], summary: {} },
reused: false,
}));
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-2' ? 'review_required' : 'review_required',
summary: {},
items: [{ case_no: runNo === 'RUN-2' ? 'CASE-2' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getExtractionRun.mockImplementation(async (runNo: string) => {
reparsePollCount += 1;
const ready = runNo === 'RUN-2' && reparsePollCount >= 2;
return {
run_no: runNo,
status: ready ? 'review_required' : 'extracting',
current_activity: { user_visible_stage: ready ? 'review_required' : 'extracting' },
};
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
}));
api.getWorkflowItem.mockImplementation(async () => {
if (reparseStarted) reparsePollCount += 1;
const ready = reparseStarted && reparsePollCount > 2;
return {
item_no: 'SWI-1',
current_run_no: ready ? 'RUN-2' : 'RUN-1',
current_case_no: ready ? 'CASE-2' : 'CASE-1',
lifecycle_status: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
current_stage: ready ? 'pending_review' : (reparseStarted ? 'extracting' : 'pending_review'),
current_version_no: ready ? 2 : 1,
};
});
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
@@ -638,8 +671,8 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.reparseProgressActive.value).toBe(true);
await vi.advanceTimersByTimeAsync(2600);
await Promise.resolve();
// 关键断言:新版指针就绪后自动停止轮询并加载新的 Run/Case。
expect(review.reparseProgressStage.value).toBe('draft_ready');
expect(review.reparseProgressPolling.value).toBe(false);
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
@@ -648,13 +681,49 @@ describe('useShippingOrderReview build eligibility writes', () => {
vi.useRealTimers();
});
it('refreshes the work item before resolving the current version target', async () => {
it('loads a partially completed reparse result and clears the read-only progress state', async () => {
vi.useFakeTimers();
api.reparseDocument.mockImplementation(async () => ({
run: { run_no: 'RUN-PARTIAL', items: [], summary: {} },
reused: false,
}));
api.getRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
summary: {},
items: [{ case_no: runNo === 'RUN-PARTIAL' ? 'CASE-PARTIAL' : 'CASE-1', status: 'draft', issue_count: 0 }],
}));
api.getExtractionRun.mockImplementation(async (runNo: string) => ({
run_no: runNo,
status: runNo === 'RUN-PARTIAL' ? 'partially_completed' : 'review_required',
current_activity: { user_visible_stage: 'review_required' },
}));
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-PARTIAL' ? 'RUN-PARTIAL' : 'RUN-1',
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
api.getWorkflowItem.mockResolvedValue({
item_no: 'SWI-1', current_run_no: 'RUN-2', current_case_no: 'CASE-2',
lifecycle_status: 'pending_review', current_stage: 'pending_review', current_version_no: 2,
});
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-PARTIAL');
expect(review.activeCase.value?.case_no).toBe('CASE-PARTIAL');
expect(review.reparseProgressStage.value).toBe('draft_ready');
expect(review.reparseProgressPolling.value).toBe(false);
expect(review.reparseProgressActive.value).toBe(false);
expect(review.isReadOnly.value).toBe(false);
expect(review.statusMessage.value).not.toBe('reparse_in_progress');
review.stopReparseProgressPolling();
vi.useRealTimers();
});
it('resolves the replacement run when superseded_by_run_no is set', async () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
api.getRun.mockResolvedValue({
run_no: 'RUN-2', summary: {}, items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
});
@@ -666,22 +735,49 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('resolves the replacement run when the historical item still points at the open case', async () => {
api.getRun.mockImplementation(async (runNo: string) => runNo === 'RUN-1'
? {
run_no: 'RUN-1',
summary: {},
items: [{ case_no: 'CASE-1', status: 'superseded', issue_count: 0 }],
}
: {
run_no: 'RUN-2',
summary: {},
items: [{ case_no: 'CASE-2', status: 'draft', issue_count: 0 }],
});
api.getCase.mockImplementation(async (caseNo: string) => buildCase({
case_no: caseNo,
run_no: caseNo === 'CASE-2' ? 'RUN-2' : 'RUN-1',
status: caseNo === 'CASE-2' ? 'draft' : 'superseded',
}));
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
review.reviewRun.value!.superseded_by_run_no = 'RUN-2';
const target = await review.openCurrentVersion();
expect(target).toEqual({ runNo: 'RUN-2', caseNo: 'CASE-2' });
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
expect(review.activeCase.value?.case_no).toBe('CASE-2');
});
it('shows a terminal failed stage when reparse fails', async () => {
vi.useFakeTimers();
api.reparseDocument.mockResolvedValue({
run: { run_no: 'RUN-FAILED', items: [], summary: {} }, reused: false,
});
api.getWorkflowItem.mockResolvedValue({
item_no: 'SWI-1', current_run_no: 'RUN-1', current_case_no: 'CASE-1',
lifecycle_status: 'reparse_failed', current_stage: 'reparse_failed', current_version_no: 1,
});
api.getExtractionRun.mockResolvedValue({ run_no: 'RUN-FAILED', status: 'failed' });
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.runAllTicks();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
await vi.advanceTimersByTimeAsync(2600);
await Promise.resolve();
// 关键断言:失败必须成为明确终态,不能继续伪装为字段提取进行中。
expect(review.reparseProgressStage.value).toBe('failed');
expect(review.reparseProgressPolling.value).toBe(false);
review.stopReparseProgressPolling();
@@ -708,18 +804,9 @@ describe('inventory routing recovery', () => {
});
api.getEvidence.mockResolvedValue({ items: [] });
api.getPreview.mockResolvedValue(new Blob());
api.listWorkflows.mockResolvedValue({ conversation_id: 'conv-1', workflows: [] });
api.getWorkflowItem.mockResolvedValue({
item_no: 'WFI-1',
workflow_no: 'WF-1',
root_document_id: 1,
current_document_id: 1,
current_version_no: 1,
current_case_no: 'CASE-1',
lifecycle_status: 'pending_review',
current_stage: 'pending_review',
lock_version: 1,
});
api.getProcessingWorkItem.mockRejectedValue(
Object.assign(new Error('not found'), { name: 'BusinessError', status: 404, code: 'NOT_FOUND' }),
);
api.getCase.mockResolvedValue(buildCase());
});
File diff suppressed because it is too large. Load diff
@@ -7,9 +7,19 @@
import { describe, expect, it } from 'vitest';
import {
mapLifecycleToNodeStatus,
mapShippingProcessingStatusToTaskGroup,
mergeConversationProcessingFocusMetadata,
projectConversationProcessingFromWorkItems,
projectConversationProcessingObjects,
projectConversationProcessingTasks,
groupConversationProcessingTasks,
mapUserTaskObjectsToFileRows,
resolveConversationProcessingFromUnified,
} from './conversationProcessingProjection';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
import type {
ShippingProcessingProjection,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
function item(partial: Partial<ShippingWorkflowItem>): ShippingWorkflowItem {
return {
@@ -84,4 +94,581 @@ describe('conversationProcessingProjection', () => {
// 关键断言:侧栏 Task 使用后端权威 node_status,不覆盖为 running。
expect(rows.find((row) => row.kind === 'task')?.node_status).toBe('manual_takeover');
});
it('groups tasks into needs_action / processing / completed; closed stays history', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 1,
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 2,
lifecycle_status: 'extracting',
current_document_filename: 'b.pdf',
}),
item({
item_no: 'WI-DONE',
current_run_no: 'RUN-DONE',
root_document_id: 3,
lifecycle_status: 'completed',
current_document_filename: 'done.pdf',
}),
item({
item_no: 'WI-C',
current_run_no: 'RUN-C',
root_document_id: 4,
lifecycle_status: 'closed',
current_document_filename: 'c.pdf',
}),
item({
item_no: 'WI-NO-NAME',
current_run_no: 'RUN-NO-NAME',
root_document_id: 5,
lifecycle_status: 'extracting',
current_document_filename: null,
}),
]);
const projection = groupConversationProcessingTasks(tasks, { focusedTaskNo: 'OT-RUN-A' });
// 右侧总数不含 history;completed 独立成组。
expect(projection.summary).toEqual({
total_tasks: 4,
total_files: 4,
processing: 2,
needs_action: 1,
completed: 1,
history: 1,
});
expect(projection.needs_action[0]?.user_task_no).toBe('OT-RUN-A');
expect(projection.processing.map((t) => t.user_task_no).sort()).toEqual([
'OT-RUN-B',
'OT-RUN-NO-NAME',
]);
expect(projection.completed?.[0]?.user_task_no).toBe('OT-RUN-DONE');
expect(projection.history[0]?.user_task_no).toBe('OT-RUN-C');
// [UI-02] 缺文件名时 title 为空,交给卡片回退「未命名 PDF」。
const unnamed = projection.processing.find((t) => t.user_task_no === 'OT-RUN-NO-NAME');
expect(unnamed?.title).toBeNull();
});
it('uses multi_document_task when one run has two different PDFs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-MULTI',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-MULTI',
lifecycle_status: 'extracting',
current_document_filename: '4518838152.pdf',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-MULTI',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-MULTI',
lifecycle_status: 'layout_parsing',
current_document_filename: '4518838154.pdf',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.document_names).toEqual(['4518838152.pdf', '4518838154.pdf']);
const docs = (tasks[0]?.objects || []).filter((row) => row.kind === 'document');
expect(docs).toHaveLength(2);
});
it('keeps multi PDF when same OT spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'a.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-2',
current_run_no: 'RUN-B',
root_document_id: 92,
current_document_id: 92,
content_hash: 'hash-b',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'b.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
// 同 OT 跨 Run 时按 PDF 身份选最新版;未在新 Run 重识别的 PDF 继续有效。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(2);
expect(tasks[0]?.display_kind).toBe('multi_document_task');
expect(tasks[0]?.title).toBeNull();
expect(tasks[0]?.document_names).toEqual(['a.pdf', 'b.pdf']);
expect(tasks[0]?.run_no).toBe('RUN-B');
const documents = tasks[0]?.objects.filter((row) => row.kind === 'document') || [];
expect(documents.map((row) => row.current_run_no)).toEqual(['RUN-A', 'RUN-B']);
});
it('keeps only latest version when same PDF spans different run_nos', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-A',
root_document_id: 91,
current_document_id: 91,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'failed',
current_document_filename: 'old.pdf',
last_activity_at: '2026-08-04T01:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-B',
root_document_id: 91,
current_document_id: 191,
content_hash: 'hash-a',
user_task_no: 'OT-SHARED',
lifecycle_status: 'pending_review',
current_document_filename: 'latest.pdf',
last_activity_at: '2026-08-04T02:00:00Z',
}),
]);
expect(tasks).toHaveLength(1);
expect(tasks[0]?.file_count).toBe(1);
expect(tasks[0]?.title).toBe('latest.pdf');
const document = tasks[0]?.objects.find((row) => row.kind === 'document');
expect(document?.document_id).toBe(191);
expect(document?.current_run_no).toBe('RUN-B');
});
it('keeps single PDF filename title for one-document run', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-ONE',
root_document_id: 7,
content_hash: 'solo',
user_task_no: 'OT-ONE',
lifecycle_status: 'extracting',
current_document_filename: 'solo.pdf',
}),
]);
expect(tasks[0]?.title).toBe('solo.pdf');
expect(tasks[0]?.display_kind).toBe('single_document_task');
expect(tasks[0]?.file_count).toBe(1);
});
it('merges same root_document_id across runs into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 42,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 42,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同 root 只保留当前有效版本(处理中),旧失败不再单独出卡。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.needs_action).toHaveLength(0);
expect(projection.processing[0]?.run_no).toBe('RUN-NEW');
expect(projection.processing[0]?.title).toBe('order.pdf');
});
it('merges different root_document_id with same content_hash into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
content_hash: 'aaa111',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
content_hash: 'aaa111',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 普通重传换 root,但同内容哈希只保留当前有效版本。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
});
it('merges different root_document_id with same user_task_no into one fallback task', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 301,
user_task_no: 'OT-SHARED',
content_hash: 'hash-a',
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 302,
user_task_no: 'OT-SHARED',
content_hash: 'hash-b',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// user_task_no 优先于 content_hash / root;输出必须原样保留真实 OT。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing[0]?.run_no).toBe('RUN-B');
expect(projection.processing[0]?.user_task_no).toBe('OT-SHARED');
expect(projection.processing[0]?.user_task_authoritative).toBe(true);
});
it('preserves authoritative user_task_no for focus/viewed APIs', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-XXX',
root_document_id: 55,
user_task_no: 'OT-REAL-001',
content_hash: 'abc',
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
// [UI-01] 禁止输出伪造 OT-${runNo},否则 focus/viewed 会打到不存在的任务号。
expect(tasks).toHaveLength(1);
expect(tasks[0]?.user_task_no).toBe('OT-REAL-001');
expect(tasks[0]?.user_task_no).not.toBe('OT-RUN-XXX');
expect(tasks[0]?.user_task_authoritative).toBe(true);
});
it('marks fabricated fallback task no as non-authoritative', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-1',
current_run_no: 'RUN-LOCAL',
root_document_id: 66,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
}),
]);
expect(tasks[0]?.user_task_no).toBe('OT-RUN-LOCAL');
expect(tasks[0]?.user_task_authoritative).toBe(false);
});
it('does not merge different root_document_id with same filename', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-A',
current_run_no: 'RUN-A',
root_document_id: 101,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-B',
current_run_no: 'RUN-B',
root_document_id: 202,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-01] 同名不同内容(不同 root)不得合并成一张卡。
expect(projection.summary.total_tasks).toBe(2);
expect(projection.processing).toHaveLength(2);
});
it('prefers newer failed over older processing for same identity', () => {
const tasks = projectConversationProcessingTasks([
item({
item_no: 'WI-OLD',
current_run_no: 'RUN-OLD',
root_document_id: 77,
lifecycle_status: 'extracting',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T10:00:00Z',
}),
item({
item_no: 'WI-NEW',
current_run_no: 'RUN-NEW',
root_document_id: 77,
lifecycle_status: 'failed',
current_document_filename: 'order.pdf',
last_activity_at: '2026-08-03T11:00:00Z',
}),
]);
const projection = groupConversationProcessingTasks(tasks);
// [UI-02] 最新有效版本按活动时间,不按 processing 严重度遮盖新失败。
expect(projection.summary.total_tasks).toBe(1);
expect(projection.processing).toHaveLength(0);
expect(projection.needs_action).toHaveLength(1);
expect(projection.needs_action[0]?.run_no).toBe('RUN-NEW');
expect(projection.needs_action[0]?.status_label).toBe('failed');
});
it('synthesizes conversation groups from unified order_task work_items', () => {
const workItems: ShippingProcessingProjection[] = [
{
workItemType: 'order_intake',
workItemNo: 'SNI-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: null,
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'failed',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['retry_parse'],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 0,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-WAIT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-WAIT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-2',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 2,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
blockingReasonCode: 'review_case_draft',
attemptNo: 0,
},
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 2,
parsedDocumentCount: 2,
candidateCount: 1,
customerName: 'ACME',
poNumber: 'PO-1',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-RUN',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-RUN',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-2',
intakeNo: 'SNI-3',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T02:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'solo.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
},
];
expect(mapShippingProcessingStatusToTaskGroup(workItems[1]!)).toBe('needs_action');
expect(mapShippingProcessingStatusToTaskGroup(workItems[2]!)).toBe('processing');
const projection = projectConversationProcessingFromWorkItems(workItems);
// 关键断言:仅 order_task 入组;intake 不进入 conversation groups。
expect(projection).not.toBeNull();
expect(projection!.needs_action.map((t) => t.user_task_no)).toEqual(['OT-WAIT']);
expect(projection!.processing.map((t) => t.user_task_no)).toEqual(['OT-RUN']);
expect(projection!.needs_action[0]?.file_count).toBe(2);
expect(projection!.needs_action[0]?.display_kind).toBe('multi_document_task');
});
it('prefers work_items task lists over embedded conversation_processing when both exist', () => {
const workItems: ShippingProcessingProjection[] = [
{
workItemType: 'order_task',
workItemNo: 'OT-ROOT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'root.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-ROOT',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-SIBLING',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'candidate_creating',
progressVersion: 1,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'sibling.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-SIB',
},
childOrderTasks: [],
},
];
const embedded = {
summary: {
total_tasks: 1,
total_files: 1,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
focused_task_no: 'OT-ROOT',
recent_task_no: 'OT-SIBLING',
needs_action: [{
user_task_no: 'OT-ROOT',
group: 'needs_action',
can_append: false,
file_count: 1,
}],
processing: [],
completed: [],
history: [],
};
const projection = resolveConversationProcessingFromUnified(workItems, embedded);
// 关键断言:兄弟 OT 仅出现在 work_items;embedded 缺 sibling 时不得覆盖任务列表。
expect(projection?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(projection?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(projection?.focused_task_no).toBe('OT-ROOT');
expect(projection?.recent_task_no).toBe('OT-SIBLING');
});
it('merges focus metadata from embedded onto work_items-derived projection', () => {
const derived = projectConversationProcessingFromWorkItems([{
workItemType: 'order_task',
workItemNo: 'OT-1',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-1',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'document_parsing',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: 'a.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 0,
customerName: null,
poNumber: null,
},
childOrderTasks: [],
}]);
const merged = mergeConversationProcessingFocusMetadata(derived, {
summary: derived!.summary,
focused_task_no: 'OT-FOCUS',
recent_task_no: 'OT-RECENT',
needs_action: [{ user_task_no: 'OT-STALE', group: 'needs_action', can_append: false }],
processing: [],
history: [],
});
expect(merged?.processing[0]?.user_task_no).toBe('OT-1');
expect(merged?.focused_task_no).toBe('OT-FOCUS');
expect(merged?.recent_task_no).toBe('OT-RECENT');
});
});
@@ -1,17 +1,56 @@
/**
* features/chat/shipping/conversationProcessingProjection.ts
* 用途:将现有 Workflow Items 投影为对话「本次处理中」统一对象行。
* 依赖:shipping.api.types(ConversationProcessingObject / WorkflowNodeStatus)。
* 逻辑:Timeline 复用本投影;Task 优先消费后端 node_status / progress_nodes;
* 不伪造进度百分比。
* 用途:将 OT / 统一 processing 投影为对话「本次处理中」对象、任务分组与文件行。
* 依赖:shipping.api.types(ConversationProcessingObject / UserTask / WorkflowNodeStatus /
* ShippingProcessingProjection、合成 ShippingWorkflowItem)。
* 逻辑:Timeline 与 ShippingConversationProcessingCard 复用;文件明细由
* mapUserTaskObjectsToFileRows(task.objects) 合成;禁止 Workflow fallback reconcile;
* 可由统一 work_items(order_task)合成兼容分组。
*/
import type {
ConversationProcessingObject,
ConversationProcessingProjection,
ConversationProcessingSummary,
ConversationProcessingTaskGroup,
ConversationProcessingUserTask,
ShippingProcessingProjection,
ShippingWorkflowItem,
WorkflowNodeStatus,
} from '@/features/chat/types/shipping.api.types';
/** 需要人工处理的生命周期集合。 */
const NEEDS_ACTION_LIFECYCLES = new Set([
'pending_review',
'manual_upload_pending',
'failed',
'reparse_failed',
'upload_rpa_failed',
]);
/** 处理中生命周期集合。 */
const PROCESSING_LIFECYCLES = new Set([
'queued',
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
'upload_rpa_pending',
'upload_rpa_running',
]);
/** 历史生命周期集合(已关闭/取消;completed 单独进「已完成」通知组)。 */
const HISTORY_LIFECYCLES = new Set([
'closed',
'cancelled',
]);
/** 识别完成、仍应在右侧展示的成功通知生命周期。 */
const COMPLETED_LIFECYCLES = new Set([
'completed',
]);
/**
* 将生命周期状态映射为 WorkflowNodeStatus(展示用,非进度百分比)。
*/
@@ -58,6 +97,59 @@ export function resolveItemDisplayStatus(item: ShippingWorkflowItem): string {
return String(item.lifecycle_status || '').trim();
}
/**
* 将 OT 任务卡内 document objects 映射为侧栏文件行(合成 ShippingWorkflowItem 形态)。
* 核心逻辑:仅消费 kind=document;item_no 优先 workflow_item_no / object_key;
* available_actions / reparse_kind 可从 object 扩展字段透传(单测与后端可选投影)。
*
* @param task - 当前展开的用户可见任务
* @returns 文件明细行;无文档对象时为空数组
*/
export function mapUserTaskObjectsToFileRows(
task: ConversationProcessingUserTask | null | undefined,
): ShippingWorkflowItem[] {
if (!task) return [];
const rows: ShippingWorkflowItem[] = [];
for (const [index, object] of (task.objects || []).entries()) {
if (object.kind !== 'document') continue;
const documentId = Number(object.document_id || 0);
const rootId = Number(object.root_document_id || documentId || 0);
const status = String(object.status_label || task.status_label || 'queued').trim() || 'queued';
const itemNo = String(
object.workflow_item_no || object.object_key || `DOC-${documentId || index + 1}`,
).trim();
const extra = object as ConversationProcessingObject & {
available_actions?: string[];
reparse_kind?: string | null;
lock_version?: number;
};
rows.push({
item_no: itemNo,
workflow_no: String(task.workflow_no || 'SNWF-OT').trim() || 'SNWF-OT',
conversation_id: '',
root_document_id: rootId,
current_document_id: documentId || rootId,
current_document_filename: object.filename || object.label || null,
content_hash: object.content_hash || null,
current_version_no: Number(object.current_version_no || 1) || 1,
current_run_no: object.current_run_no || object.run_no || task.run_no || null,
current_case_no: object.case_no || null,
current_task_no: object.task_no || task.user_task_no || null,
user_task_no: task.user_task_no,
user_task_authoritative: task.user_task_authoritative,
lifecycle_status: status,
current_stage: status,
display_lifecycle_status: status,
lock_version: Number(extra.lock_version || 1) || 1,
available_actions: Array.isArray(extra.available_actions)
? extra.available_actions
: (Array.isArray(task.available_actions) ? task.available_actions : undefined),
reparse_kind: extra.reparse_kind ?? null,
});
}
return rows;
}
/**
* 从 Workflow Items 聚合 Run / Candidate / Task / Process Gate 侧栏行。
*
@@ -188,3 +280,416 @@ export function projectConversationProcessingObjects(
return rows;
}
/**
* 按生命周期/门禁将状态归入 needs_action | processing | completed | history。
*/
export function classifyConversationProcessingGroup(
status: string | null | undefined,
options?: { hasBlockingGate?: boolean; needsCustomerConfirm?: boolean },
): ConversationProcessingTaskGroup {
if (options?.hasBlockingGate || options?.needsCustomerConfirm) return 'needs_action';
const normalized = String(status || '').trim();
if (NEEDS_ACTION_LIFECYCLES.has(normalized)) return 'needs_action';
if (COMPLETED_LIFECYCLES.has(normalized)) return 'completed';
if (HISTORY_LIFECYCLES.has(normalized)) return 'history';
if (PROCESSING_LIFECYCLES.has(normalized)) return 'processing';
if (normalized === 'review_required' || normalized === 'partially_completed') {
return 'needs_action';
}
if (normalized === 'failed' || normalized === 'cancelled') return 'needs_action';
if (normalized === 'completed') return 'completed';
if (normalized === 'processing' || normalized === 'queued') return 'processing';
return 'processing';
}
/**
* 兜底任务身份键:稳定业务身份优先,文件名仅作最弱兜底。
* 顺序:user_task_no → content_hash → root_document_id → filename → run/item。
* 普通重传会换 root_document_id,故不得把 root 放在 content_hash 之前。
*/
function fallbackTaskIdentityKey(item: ShippingWorkflowItem): string {
const userTaskNo = String(item.user_task_no || '').trim();
if (userTaskNo) return `task:${userTaskNo}`;
const contentHash = String(item.content_hash || '').trim().toLowerCase();
if (contentHash) return `hash:${contentHash}`;
const rootId = Number(item.root_document_id || 0);
if (rootId > 0) return `root:${rootId}`;
const filename = String(item.current_document_filename || '').trim().toLowerCase();
if (filename) return `fn:${filename}`;
const runNo = String(item.current_run_no || '').trim();
if (runNo) return `run:${runNo}`;
return `item:${String(item.item_no || '').trim()}`;
}
/**
* 降级路径:按稳定身份去重 Workflow Items 中的业务 PDF。
* 顺序:content_hash → root_document_id → current_document_id;禁止仅按文件名去重。
*/
function dedupeFallbackDocuments(items: ShippingWorkflowItem[]): Array<{
filename: string | null;
content_hash: string | null;
root_document_id: number;
document_id: number;
status_label: string;
current_run_no: string | null;
source_item: ShippingWorkflowItem;
}> {
const unique: Array<{
filename: string | null;
content_hash: string | null;
root_document_id: number;
document_id: number;
status_label: string;
current_run_no: string | null;
source_item: ShippingWorkflowItem;
recency: number;
identity: string;
}> = [];
const seen = new Map<string, number>();
for (const item of items || []) {
const contentHash = String(item.content_hash || '').trim().toLowerCase();
const rootId = Number(item.root_document_id || 0);
const documentId = Number(item.current_document_id || 0);
const identity = contentHash
? `hash:${contentHash}`
: rootId > 0
? `root:${rootId}`
: documentId > 0
? `doc:${documentId}`
: `item:${String(item.item_no || '').trim()}`;
const filename = String(item.current_document_filename || '').trim() || null;
const row = {
filename,
content_hash: contentHash || null,
root_document_id: rootId,
document_id: documentId,
status_label: resolveItemDisplayStatus(item),
current_run_no: String(item.current_run_no || '').trim() || null,
source_item: item,
recency: Date.parse(String(item.last_activity_at || item.updated_at || '').trim()) || 0,
identity,
};
const existingIndex = seen.get(identity);
if (existingIndex == null) {
seen.set(identity, unique.length);
unique.push(row);
continue;
}
const existing = unique[existingIndex]!;
if (row.recency > existing.recency
|| (row.recency === existing.recency && documentId >= existing.document_id)) {
unique[existingIndex] = row;
}
}
return unique;
}
/**
* 从 Workflow Items 聚合为用户可见任务列表(后端 processing 未就绪时的前端兜底)。
* 核心逻辑:先按稳定任务身份(user_task_no / hash…)归并全部 Item,再按 PDF 去重计
* file_count;禁止先按 run_no 拆桶再丢弃同 OT 的另一份 PDF;单 PDF 才用文件名作 title。
*/
export function projectConversationProcessingTasks(
items: ShippingWorkflowItem[],
options?: {
focusTaskNo?: string | null;
focusRunNo?: string | null;
focusUserTaskNo?: string | null;
},
): ConversationProcessingUserTask[] {
const byIdentity = new Map<string, ShippingWorkflowItem[]>();
for (const item of items || []) {
const identity = fallbackTaskIdentityKey(item);
if (!identity || identity === 'item:') continue;
const bucket = byIdentity.get(identity) || [];
bucket.push(item);
byIdentity.set(identity, bucket);
}
const focusUserTask = String(options?.focusUserTaskNo || '').trim();
const focusRun = String(options?.focusRunNo || '').trim();
const tasks: ConversationProcessingUserTask[] = [];
for (const [identity, groupItems] of byIdentity) {
void identity;
if (!groupItems.length) continue;
// [STEP 1] 取最近活动 Item 作为任务级代表 Run;PDF 则跨 Run 独立选择最新版本。
const sorted = [...groupItems].sort((a, b) => {
const aAt = Date.parse(String(a.last_activity_at || a.updated_at || '').trim()) || 0;
const bAt = Date.parse(String(b.last_activity_at || b.updated_at || '').trim()) || 0;
if (bAt !== aAt) return bAt - aAt;
return String(b.current_run_no || '').localeCompare(String(a.current_run_no || ''));
});
const primaryItem = sorted[0];
if (!primaryItem) continue;
const runNo = String(
primaryItem.current_run_no || primaryItem.workflow_no || primaryItem.item_no || '',
).trim();
// [STEP 2] 同 OT 的旧 Run 仍可能承载未重识别 PDF,禁止整批过滤到代表 Run。
const uniqueDocuments = dedupeFallbackDocuments(groupItems);
const effectiveItems = uniqueDocuments.map((row) => row.source_item);
// 任务级分组/操作只由最近代表 Item 决定;旧 Run 仅贡献未受影响的 PDF,不得反向污染状态。
const statuses = [resolveItemDisplayStatus(primaryItem)];
const hasGate = Boolean(primaryItem.process_gate?.current_blocking_gate);
let group: ConversationProcessingTaskGroup = 'history';
for (const status of statuses) {
const g = classifyConversationProcessingGroup(status, { hasBlockingGate: hasGate });
if (g === 'needs_action') {
group = 'needs_action';
break;
}
if (g === 'processing') {
group = 'processing';
continue;
}
if (g === 'completed' && group !== 'processing') {
group = 'completed';
}
}
const primaryStatus = statuses.find((s) => NEEDS_ACTION_LIFECYCLES.has(s))
|| statuses.find((s) => PROCESSING_LIFECYCLES.has(s))
|| statuses.find((s) => COMPLETED_LIFECYCLES.has(s))
|| statuses[0]
|| 'queued';
// [UI-01] 必须原样输出后端真实 OT;仅缺省时才用本地兼容号,且不得用于写接口。
const authoritativeTaskNo = String(
effectiveItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|| groupItems.map((row) => row.user_task_no).find((value) => String(value || '').trim())
|| '',
).trim();
const userTaskNo = authoritativeTaskNo || `OT-${runNo}`;
const documentNames = uniqueDocuments
.map((row) => String(row.filename || '').trim())
.filter(Boolean);
const isMulti = uniqueDocuments.length > 1;
const title = isMulti
? null
: (documentNames[0] || String(primaryItem.current_document_filename || '').trim() || null);
const activityRaw = String(primaryItem.last_activity_at || primaryItem.updated_at || '').trim();
const documentObjects = uniqueDocuments.map((row) => ({
kind: 'document' as const,
object_key: row.document_id > 0
? `DOC-${row.document_id}`
: `DOC-${row.root_document_id || row.filename || 'unknown'}`,
label: row.filename || `DOC-${row.document_id || row.root_document_id}`,
status_label: row.status_label,
document_id: row.document_id || null,
root_document_id: row.root_document_id || null,
filename: row.filename,
content_hash: row.content_hash,
run_no: row.current_run_no,
current_run_no: row.current_run_no,
user_task_no: userTaskNo,
focused: false,
}));
tasks.push({
user_task_no: userTaskNo,
user_task_authoritative: Boolean(authoritativeTaskNo),
title,
display_kind: isMulti ? 'multi_document_task' : 'single_document_task',
document_names: documentNames,
group,
status_label: primaryStatus,
file_count: uniqueDocuments.length,
run_no: runNo || null,
workflow_no: String(primaryItem.workflow_no || '').trim() || null,
can_append: false,
append_block_reason: 'input_already_frozen',
last_activity_at: activityRaw || null,
focused: Boolean(
(focusUserTask && focusUserTask === userTaskNo)
|| (focusRun && focusRun === runNo),
),
objects: [
...projectConversationProcessingObjects(effectiveItems, {
focusTaskNo: options?.focusTaskNo,
focusRunNo: runNo,
}),
...documentObjects,
],
});
}
return tasks;
}
/**
* 将任务列表按分组装入 ConversationProcessingProjection。
*/
export function groupConversationProcessingTasks(
tasks: ConversationProcessingUserTask[],
options?: {
focusedTaskNo?: string | null;
recentTaskNo?: string | null;
},
): ConversationProcessingProjection {
const needs_action = tasks.filter((t) => t.group === 'needs_action');
const processing = tasks.filter((t) => t.group === 'processing');
const completed = tasks.filter((t) => t.group === 'completed');
const history = tasks.filter((t) => t.group === 'history');
const active = [...needs_action, ...processing, ...completed];
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
const summary: ConversationProcessingSummary = {
total_tasks: needs_action.length + processing.length + completed.length,
total_files: totalFiles,
processing: processing.length,
needs_action: needs_action.length,
completed: completed.length,
history: history.length,
};
return {
summary,
focused_task_no: options?.focusedTaskNo || null,
recent_task_no: options?.recentTaskNo || null,
needs_action,
processing,
completed,
history,
};
}
/**
* 用 Workflow 兜底投影补齐后端 processing 的多 PDF 标题/文件数。
* 核心逻辑:同 user_task_no / run_no 时,若兜底 file_count 更大,采用兜底的
* display_kind / title / document_names / objects(文档子对象)。
*/
/**
* 将统一 ShippingProcessing status/gate 映射为会话任务分组。
* 核心逻辑:waiting_review/blocked/failed → needs_action;completed → completed;
* cancelled → history;其余 → processing。
*/
export function mapShippingProcessingStatusToTaskGroup(
item: ShippingProcessingProjection,
): ConversationProcessingTaskGroup {
const status = String(item.status || '').trim().toLowerCase();
const gateAction = String(item.currentGate?.nextActionCode || '').trim();
if (
status === 'waiting_review'
|| status === 'blocked'
|| status === 'failed'
|| gateAction === 'open_order_review'
|| gateAction === 'retry_parse'
|| gateAction === 'retry_failed_documents'
) {
return 'needs_action';
}
if (status === 'completed') return 'completed';
if (status === 'cancelled') return 'history';
return 'processing';
}
/**
* 将 embedded conversation_processing 的焦点元数据合并到 work_items 派生投影。
* 核心逻辑:任务列表必须来自 work_items;仅 focused_task_no / recent_task_no 可取自 embedded。
*
* @param derived - 由 projectConversationProcessingFromWorkItems 生成的投影
* @param embedded - API 内嵌 conversation_processing(可选)
* @returns 合并后的投影;derived 为空时回退 embedded
*/
export function mergeConversationProcessingFocusMetadata(
derived: ConversationProcessingProjection | null,
embedded: ConversationProcessingProjection | null | undefined,
): ConversationProcessingProjection | null {
if (!derived) {
return embedded && typeof embedded === 'object' ? embedded : null;
}
if (!embedded || typeof embedded !== 'object') return derived;
return {
...derived,
focused_task_no: embedded.focused_task_no ?? derived.focused_task_no ?? null,
recent_task_no: embedded.recent_task_no ?? derived.recent_task_no ?? null,
};
}
/**
* 从统一 shipping-processing 响应解析 ConversationProcessingProjection。
* 核心逻辑:work_items 非空时始终由 order_task 工作项合成任务列表;禁止优先 embedded
* (兄弟 OT 仅出现在 work_items,embedded 可能缺 sibling)。
*
* @param workItems - unified.work_items
* @param embedded - unified.conversation_processing
* @returns 会话处理投影;无可用数据时 null
*/
export function resolveConversationProcessingFromUnified(
workItems: ShippingProcessingProjection[] | null | undefined,
embedded: ConversationProcessingProjection | null | undefined,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
if (items.length > 0) {
return mergeConversationProcessingFocusMetadata(
projectConversationProcessingFromWorkItems(items),
embedded,
);
}
if (embedded && typeof embedded === 'object') return embedded;
return null;
}
/**
* 从统一 work_items 合成 ConversationProcessingProjection(仅 order_task)。
*
* 核心逻辑:order_task 工作项填充 needs_action/processing/completed;intake 不入组。
*
* @param workItems - 统一投影 work_items
* @returns 兼容投影;无 order_task 时返回 null
*/
export function projectConversationProcessingFromWorkItems(
workItems: ShippingProcessingProjection[] | null | undefined,
): ConversationProcessingProjection | null {
const items = Array.isArray(workItems) ? workItems : [];
const orderTasks = items.filter((row) => row.workItemType === 'order_task');
if (!orderTasks.length) return null;
const needs_action: ConversationProcessingUserTask[] = [];
const processing: ConversationProcessingUserTask[] = [];
const completed: ConversationProcessingUserTask[] = [];
const history: ConversationProcessingUserTask[] = [];
for (const item of orderTasks) {
const taskNo = String(item.workItemNo || item.rootOrderTaskNo || '').trim();
if (!taskNo) continue;
const group = mapShippingProcessingStatusToTaskGroup(item);
const docCount = Number(item.sourceSummary?.documentCount || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
const task: ConversationProcessingUserTask = {
user_task_no: taskNo,
user_task_authoritative: true,
title: filename || null,
display_kind: docCount > 1 ? 'multi_document_task' : 'single_document_task',
document_names: filename ? [filename] : [],
group,
status_label: String(item.status || '') || null,
file_count: docCount > 0 ? docCount : (filename ? 1 : 0),
run_no: null,
can_append: false,
last_activity_at: item.lastActivityAt || null,
available_actions: Array.isArray(item.availableActions) ? [...item.availableActions] : [],
primary_action: item.currentGate?.nextActionCode || item.availableActions?.[0] || null,
};
if (group === 'needs_action') needs_action.push(task);
else if (group === 'processing') processing.push(task);
else if (group === 'completed') completed.push(task);
else history.push(task);
}
const active = [...needs_action, ...processing, ...completed];
if (!active.length && !history.length) return null;
const totalFiles = active.reduce((sum, task) => sum + Number(task.file_count || 0), 0);
return {
summary: {
total_tasks: active.length,
total_files: totalFiles,
processing: processing.length,
needs_action: needs_action.length,
completed: completed.length,
history: history.length,
},
focused_task_no: null,
recent_task_no: null,
needs_action,
processing,
completed,
history,
};
}
@@ -0,0 +1,62 @@
/**
* features/chat/shipping/conversationProcessingState.spec.ts
* 用途:验收会话「本次处理中」焦点/查看/折叠状态不被普通轮询覆盖。
* 依赖:Vitest、conversationProcessingState。
* 逻辑:手动焦点优先于服务端;toggle 详情互斥;history 展开独立。
*/
import { describe, expect, it } from 'vitest';
import {
createConversationProcessingUiState,
focusTaskManually,
markTaskViewed,
resolveFocusedTask,
shouldExpandTaskDetails,
toggleTaskDetails,
} from './conversationProcessingState';
describe('conversationProcessingState', () => {
it('prefers manual focus over server focused / recent', () => {
const state = createConversationProcessingUiState();
focusTaskManually(state, 'OT-2', { expandDetails: true });
expect(resolveFocusedTask(state, {
serverFocusedTaskNo: 'OT-1',
recentTaskNo: 'OT-3',
})).toBe('OT-2');
expect(state.expandedDetailTaskNo).toBe('OT-2');
});
it('falls back to server then recent when no manual focus', () => {
const state = createConversationProcessingUiState();
expect(resolveFocusedTask(state, {
serverFocusedTaskNo: 'OT-1',
recentTaskNo: 'OT-3',
})).toBe('OT-1');
expect(resolveFocusedTask(state, { recentTaskNo: 'OT-3' })).toBe('OT-3');
});
it('marks viewed without implying resolved', () => {
const state = createConversationProcessingUiState();
markTaskViewed(state, 'OT-9');
expect(state.viewedTaskNos.has('OT-9')).toBe(true);
});
it('toggles file details and keeps only one expanded task', () => {
const state = createConversationProcessingUiState();
toggleTaskDetails(state, 'OT-A');
expect(state.expandedDetailTaskNo).toBe('OT-A');
toggleTaskDetails(state, 'OT-B');
expect(state.expandedDetailTaskNo).toBe('OT-B');
toggleTaskDetails(state, 'OT-B');
expect(state.expandedDetailTaskNo).toBeNull();
});
it('expands only when user explicitly toggles details', () => {
const state = createConversationProcessingUiState();
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
state.expandedDetailTaskNo = 'OT-1';
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(true);
state.expandedDetailTaskNo = 'OT-2';
expect(shouldExpandTaskDetails(state, 'OT-1', { focusedTaskNo: 'OT-1' })).toBe(false);
expect(shouldExpandTaskDetails(state, 'OT-2', { focusedTaskNo: 'OT-1' })).toBe(true);
});
});
@@ -0,0 +1,117 @@
/**
* features/chat/shipping/conversationProcessingState.ts
* 用途:管理会话「本次处理中」焦点、已查看与文件详情展开的客户端状态。
* 依赖:无 IO;由 ShippingConversationProcessingCard / useShippingNoticeWorkflow 消费。
* 逻辑:普通轮询只合并服务端摘要,不覆盖用户手动折叠/焦点;高优先级状态只高亮不抢焦点。
*/
import { reactive } from 'vue';
export interface ConversationProcessingUiState {
/** 用户主动聚焦的用户可见任务号 */
manualFocusedTaskNo: string | null;
/** 已打开过详情的任务 */
viewedTaskNos: Set<string>;
/** 文件详情展开的任务(通常至多一个) */
expandedDetailTaskNo: string | null;
/** 处理记录分组是否展开 */
historyExpanded: boolean;
}
/**
* 创建会话级 UI 状态容器(按 conversation 实例化,切会话时重建)。
*/
export function createConversationProcessingUiState(): ConversationProcessingUiState {
return reactive({
manualFocusedTaskNo: null,
viewedTaskNos: new Set<string>(),
expandedDetailTaskNo: null,
historyExpanded: false,
});
}
/**
* 重置会话级 UI 状态(切 conversation 时调用)。
*/
export function resetConversationProcessingUiState(
state: ConversationProcessingUiState,
): void {
state.manualFocusedTaskNo = null;
state.viewedTaskNos.clear();
state.expandedDetailTaskNo = null;
state.historyExpanded = false;
}
/**
* 解析有效焦点:手动焦点优先,否则用服务端 focused_task_no / recent。
*/
export function resolveFocusedTask(
state: ConversationProcessingUiState,
options?: {
serverFocusedTaskNo?: string | null;
recentTaskNo?: string | null;
},
): string | null {
const manual = String(state.manualFocusedTaskNo || '').trim();
if (manual) return manual;
const server = String(options?.serverFocusedTaskNo || '').trim();
if (server) return server;
const recent = String(options?.recentTaskNo || '').trim();
return recent || null;
}
/**
* 用户点击任务卡:设置手动焦点并可选展开详情。
*/
export function focusTaskManually(
state: ConversationProcessingUiState,
taskNo: string,
options?: { expandDetails?: boolean },
): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.manualFocusedTaskNo = normalized;
if (options?.expandDetails !== false) {
state.expandedDetailTaskNo = normalized;
}
}
/**
* 标记任务已查看(可折叠 history;不等于 resolved)。
*/
export function markTaskViewed(state: ConversationProcessingUiState, taskNo: string): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.viewedTaskNos.add(normalized);
}
/**
* 是否展开某任务文件详情:仅当用户显式展开(expandedDetailTaskNo),不因焦点自动展开。
*/
export function shouldExpandTaskDetails(
state: ConversationProcessingUiState,
taskNo: string,
options?: {
focusedTaskNo?: string | null;
forceExpand?: boolean;
},
): boolean {
const normalized = String(taskNo || '').trim();
if (!normalized) return false;
if (options?.forceExpand) return true;
return state.expandedDetailTaskNo === normalized;
}
/**
* 切换文件详情展开;同一时刻只保留一个展开任务。
*/
export function toggleTaskDetails(
state: ConversationProcessingUiState,
taskNo: string,
): void {
const normalized = String(taskNo || '').trim();
if (!normalized) return;
state.expandedDetailTaskNo = state.expandedDetailTaskNo === normalized
? null
: normalized;
}
@@ -0,0 +1,72 @@
/**
* features/chat/shipping/normalizeShippingProcessing.spec.ts
* 用途:验收 snake_case → camelCase 规范与缺字段安全默认。
* 依赖:Vitest、normalizeShippingProcessing。
*/
import { describe, expect, it } from 'vitest';
import {
normalizeShippingProcessingProjection,
normalizeShippingProcessingWorkItems,
} from './normalizeShippingProcessing';
describe('normalizeShippingProcessingProjection', () => {
it('maps snake_case backend payload to camelCase DTO', () => {
const normalized = normalizeShippingProcessingProjection({
work_item_type: 'order_task',
work_item_no: 'OT-1',
source_type: 'direct_pdf',
root_order_task_no: 'OT-1',
shipping_notice_no: null,
conversation_id: 'conv-1',
submission_no: 'SOS-1',
intake_no: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progress_version: 3,
last_activity_at: '2026-08-04T12:00:00Z',
current_gate: {
gate_code: 'field_conflict_resolution',
status: 'blocked',
next_action_code: 'resolve_field_conflicts',
blocking_reason_code: 'pdf_preferred_critical_conflict',
attempt_no: 1,
},
available_actions: ['open_review'],
source_summary: {
email_subject: null,
filename: 'a.pdf',
document_count: 1,
parsed_document_count: 1,
candidate_count: 1,
customer_name: 'ACME',
po_number: 'PO-1',
failure_reason_code: null,
parse_attempt_count: 0,
asset_status: 'ready',
},
child_order_tasks: [],
});
expect(normalized).not.toBeNull();
expect(normalized!.workItemNo).toBe('OT-1');
expect(normalized!.sourceType).toBe('direct_pdf');
expect(normalized!.status).toBe('waiting_review');
expect(normalized!.currentGate?.gateCode).toBe('field_conflict_resolution');
expect(normalized!.currentGate?.attemptNo).toBe(1);
expect(normalized!.sourceSummary.filename).toBe('a.pdf');
expect(normalized!.sourceSummary.assetStatus).toBe('ready');
expect(normalized!.availableActions).toEqual(['open_review']);
});
it('returns null when work_item_no missing', () => {
expect(normalizeShippingProcessingProjection({ status: 'processing' })).toBeNull();
});
it('normalizes work_items arrays', () => {
const items = normalizeShippingProcessingWorkItems([
{ work_item_no: 'OT-A', work_item_type: 'order_task', status: 'processing', stage: 'document_parsing' },
{ status: 'processing' },
]);
expect(items).toHaveLength(1);
expect(items[0].workItemNo).toBe('OT-A');
});
});
@@ -0,0 +1,143 @@
/**
* features/chat/shipping/normalizeShippingProcessing.ts
* 用途:将后端 snake_case ShippingProcessingProjection 规范为前端 camelCase DTO。
* 依赖:shipping.api.types ShippingProcessingProjection / ProcessGateSummary。
* 逻辑:API 边界一次性转换;透传 Gate attemptNo 与 Intake 失败恢复摘要字段。
*/
import type {
OrderIntakeSourceType,
ProcessGateSummary,
ShippingOrderTaskSummary,
ShippingProcessingProjection,
ShippingProcessingStage,
ShippingProcessingStatus,
ShippingProcessingWorkItemType,
} from '../types/shipping.api.types';
/**
* 读取原始对象上的字符串字段(兼容 snake / camel)。
*/
function readString(raw: Record<string, unknown>, snake: string, camel: string): string {
const value = raw[snake] ?? raw[camel];
return value == null ? '' : String(value);
}
/**
* 读取可空字符串。
*/
function readNullableString(
raw: Record<string, unknown>,
snake: string,
camel: string,
): string | null {
const value = raw[snake] ?? raw[camel];
if (value == null || value === '') return null;
return String(value);
}
/**
* 规范单个 OT 摘要。
*/
function normalizeChildTask(raw: unknown): ShippingOrderTaskSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const orderTaskNo = readString(item, 'order_task_no', 'orderTaskNo');
if (!orderTaskNo) return null;
return {
orderTaskNo,
status: readString(item, 'status', 'status') as ShippingProcessingStatus,
stage: readString(item, 'stage', 'stage') as ShippingProcessingStage,
customerName: readNullableString(item, 'customer_name', 'customerName'),
poNumber: readNullableString(item, 'po_number', 'poNumber'),
lastActivityAt: readNullableString(item, 'last_activity_at', 'lastActivityAt'),
};
}
/**
* 规范 Gate 摘要。
*/
function normalizeGate(raw: unknown): ProcessGateSummary | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const gateCode = readString(item, 'gate_code', 'gateCode');
if (!gateCode) return null;
return {
gateCode,
status: readString(item, 'status', 'status') || 'unknown',
nextActionCode: readNullableString(item, 'next_action_code', 'nextActionCode'),
blockingReasonCode: readNullableString(item, 'blocking_reason_code', 'blockingReasonCode'),
attemptNo: (() => {
const rawAttempt = item.attempt_no ?? item.attemptNo;
if (rawAttempt == null || rawAttempt === '') return null;
const n = Number(rawAttempt);
return Number.isFinite(n) ? n : null;
})(),
};
}
/**
* 将后端 / 混合字段投影规范为 ShippingProcessingProjection。
* 核心逻辑:缺字段给安全默认值,保证四页面可渲染;非法输入返回 null。
*
* @param raw - API 原始对象
* @returns 规范化投影;无法识别时 null
*/
export function normalizeShippingProcessingProjection(
raw: unknown,
): ShippingProcessingProjection | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const workItemNo = readString(item, 'work_item_no', 'workItemNo');
if (!workItemNo) return null;
const summaryRaw = (item.source_summary ?? item.sourceSummary ?? {}) as Record<string, unknown>;
const childrenRaw = item.child_order_tasks ?? item.childOrderTasks;
const children = Array.isArray(childrenRaw)
? childrenRaw.map(normalizeChildTask).filter((row): row is ShippingOrderTaskSummary => Boolean(row))
: [];
const actionsRaw = item.available_actions ?? item.availableActions;
const availableActions = Array.isArray(actionsRaw)
? actionsRaw.map((action) => String(action || '').trim()).filter(Boolean)
: [];
return {
workItemType: (readString(item, 'work_item_type', 'workItemType') || 'order_task') as ShippingProcessingWorkItemType,
workItemNo,
sourceType: (readNullableString(item, 'source_type', 'sourceType') || 'eml') as OrderIntakeSourceType,
rootOrderTaskNo: readNullableString(item, 'root_order_task_no', 'rootOrderTaskNo'),
shippingNoticeNo: readNullableString(item, 'shipping_notice_no', 'shippingNoticeNo'),
conversationId: readNullableString(item, 'conversation_id', 'conversationId'),
submissionNo: readString(item, 'submission_no', 'submissionNo'),
intakeNo: readString(item, 'intake_no', 'intakeNo'),
status: (readString(item, 'status', 'status') || 'processing') as ShippingProcessingStatus,
stage: (readString(item, 'stage', 'stage') || 'upload_received') as ShippingProcessingStage,
progressVersion: Number(item.progress_version ?? item.progressVersion ?? 0) || 0,
lastActivityAt: readString(item, 'last_activity_at', 'lastActivityAt'),
currentGate: normalizeGate(item.current_gate ?? item.currentGate),
availableActions,
sourceSummary: {
emailSubject: readNullableString(summaryRaw, 'email_subject', 'emailSubject'),
filename: readNullableString(summaryRaw, 'filename', 'filename'),
documentCount: Number(summaryRaw.document_count ?? summaryRaw.documentCount ?? 0) || 0,
parsedDocumentCount: Number(summaryRaw.parsed_document_count ?? summaryRaw.parsedDocumentCount ?? 0) || 0,
candidateCount: Number(summaryRaw.candidate_count ?? summaryRaw.candidateCount ?? 0) || 0,
customerName: readNullableString(summaryRaw, 'customer_name', 'customerName'),
poNumber: readNullableString(summaryRaw, 'po_number', 'poNumber'),
failureReasonCode: readNullableString(summaryRaw, 'failure_reason_code', 'failureReasonCode'),
parseAttemptCount: Number(summaryRaw.parse_attempt_count ?? summaryRaw.parseAttemptCount ?? 0) || 0,
assetStatus: readNullableString(summaryRaw, 'asset_status', 'assetStatus'),
},
childOrderTasks: children,
};
}
/**
* 将会话级统一投影响应中的 work_items 规范为数组。
*/
export function normalizeShippingProcessingWorkItems(raw: unknown): ShippingProcessingProjection[] {
if (!Array.isArray(raw)) return [];
return raw
.map(normalizeShippingProcessingProjection)
.filter((item): item is ShippingProcessingProjection => Boolean(item));
}
@@ -0,0 +1,135 @@
/**
* features/chat/shipping/shippingProcessingFulfillment.ts
*
* 用途:履约相关节点索引与人工上传 Gate 动作判定(过渡期兼容)。
* 依赖:ShippingProcessingProjection / ProcessGateSummary 的轻量字段形状。
* 逻辑:ReviewWorkflowProgressPanel、ShippingTaskWorkbench、TaskTodoPanel 共用;
* 禁止用 WorkflowItem.lifecycle 推断人工上传或节点高亮。
* FULFILLMENT_PROGRESS_NODES 四节点不是 UI 主进度真相;主真相为
* ShippingProcessingProjection 15 阶(阶段 2 换 UnifiedProgressTrack)。
*/
/** 复核/任务台共用的履约四节点 stage 键。 */
export const FULFILLMENT_PROGRESS_NODES = [
'building_order',
'inventory_matching',
'generating_excel',
'freight_uploading',
] as const;
export type FulfillmentProgressNodeKey = typeof FULFILLMENT_PROGRESS_NODES[number];
/** 指人工上传登记的任务台 / Gate 动作码(不含 RPA retry)。 */
export const MANUAL_UPLOAD_GATE_ACTIONS = new Set([
'wait_manual_upload',
'mark_manual_uploaded',
'regenerate_manual_upload_todo',
]);
/** 统一 ShippingProcessing 终态 status(停止轮询)。 */
export const TERMINAL_PROCESSING_STATUSES = new Set([
'completed',
'cancelled',
'failed',
]);
/** 统一 ShippingProcessing 非终态 status(可继续轮询)。 */
export const IN_PROGRESS_PROCESSING_STATUSES = new Set([
'queued',
'processing',
'waiting_review',
'automating',
'blocked',
'needs_action',
]);
/**
* 判定 Gate next_action / available_action 是否指人工上传登记。
*
* @param code - next_action_code 或 available_actions 项
* @returns 是否为人工上传相关动作
*/
export function isManualUploadGateAction(code: string | null | undefined): boolean {
const normalized = String(code || '').trim().toLowerCase();
return MANUAL_UPLOAD_GATE_ACTIONS.has(normalized);
}
/**
* 从统一投影判断是否需要展示任务台人工上传入口。
*
* 核心逻辑:读 currentGate.nextActionCode 与 availableActions;RPA automating /
* freight_uploading 阶段一律不算人工上传。
*
* @param projection - 统一 ShippingProcessing 投影
* @returns 是否应展示人工上传任务台入口
*/
export function projectionRequiresManualUploadWorkbench(
projection: {
status?: string | null;
stage?: string | null;
currentGate?: { nextActionCode?: string | null; blockingReasonCode?: string | null } | null;
availableActions?: string[] | null;
} | null | undefined,
): boolean {
if (!projection) return false;
const status = String(projection.status || '').trim().toLowerCase();
const stage = String(projection.stage || '').trim().toLowerCase();
if (status === 'automating' || stage === 'freight_uploading') return false;
const gate = projection.currentGate;
if (isManualUploadGateAction(gate?.nextActionCode)) return true;
const actions = Array.isArray(projection.availableActions) ? projection.availableActions : [];
return actions.some((action) => isManualUploadGateAction(action));
}
/**
* 从 Gate 摘要 / checkpoint 判断是否展示「待人工上传登记」提示。
*
* @param params.nextActionCode - process_gate 或 current_blocking_gate 的 next_action_code
* @param params.checkpointKind - ui_state.checkpoint_kind
* @param params.availableActions - 后端允许的 action 列表
* @returns 是否展示人工上传说明
*/
export function gateSummaryIndicatesManualUpload(params: {
nextActionCode?: string | null;
checkpointKind?: string | null;
availableActions?: string[] | null;
}): boolean {
if (isManualUploadGateAction(params.nextActionCode)) return true;
if (String(params.checkpointKind || '').trim() === 'wait_manual_upload') return true;
const actions = Array.isArray(params.availableActions) ? params.availableActions : [];
return actions.some((action) => isManualUploadGateAction(action));
}
/**
* 将统一 stage/status 映射到履约四节点索引(0..3)。
*
* @param stage - ShippingProcessingStage
* @param status - ShippingProcessingStatus
* @returns 当前节点索引;无法映射时返回 -1
*/
export function fulfillmentNodeIndexFromStage(
stage?: string | null,
status?: string | null,
): number {
const s = String(stage || '').trim().toLowerCase();
const st = String(status || '').trim().toLowerCase();
if (st === 'completed' || s === 'completed') return 3;
if (s === 'freight_uploading' || st === 'automating') return 3;
if (s === 'excel_generating' || s === 'generating_excel') return 2;
if (s === 'inventory_matching' || s.startsWith('inventory_')) return 1;
if (
s === 'building_order'
|| s === 'order_creating'
|| s === 'document_parsing'
|| s === 'upload_received'
|| s.startsWith('email_')
|| s === 'waiting_review'
|| s === 'customer_resolving'
|| s === 'duplicate_checking'
|| s === 'candidate_creating'
) {
return 0;
}
if (s) return 0;
return -1;
}
@@ -0,0 +1,40 @@
/**
* features/chat/shipping/shippingProcessingLabels.spec.ts
* 用途:验收统一状态文案映射到 chat.shippingProcessing。
* 依赖:Vitest、shippingProcessingLabels。
*/
import { describe, expect, it } from 'vitest';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingStatusLabel,
shippingProcessingStatusKey,
} from './shippingProcessingLabels';
describe('shippingProcessingLabels', () => {
it('bridges pending_review to waiting_review key', () => {
expect(shippingProcessingStatusKey('pending_review')).toBe(
'chat.shippingProcessing.status.waiting_review',
);
});
it('falls back to shippingProcessing.taskStatus when unified status missing', () => {
// 关键断言:旧 taskStatus 已合并进 shippingProcessing。
const te = (key: string) => key === 'chat.shippingProcessing.taskStatus.queued';
const t = (key: string) => (key.endsWith('queued') ? '排队中' : key);
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('resolves group messages from shippingProcessing', () => {
const te = (key: string) => key === 'chat.shippingProcessing.groupNeedsAction';
const t = (key: string, params?: Record<string, unknown>) => (
key.includes('groupNeedsAction') ? `需要你处理 · ${params?.count}` : key
);
expect(resolveShippingProcessingMessage('groupNeedsAction', te, t, { count: 2 })).toBe('需要你处理 · 2');
});
});
@@ -0,0 +1,114 @@
/**
* features/chat/shipping/shippingProcessingLabels.ts
* 用途:将统一 ShippingProcessing 状态/阶段码映射到四语言 i18n 键。
* 依赖:vue-i18n Composer(由调用方传入 t / te)。
* 逻辑:统一读 chat.shippingProcessing.*(含原 shippingWorkflow 合并键,如 taskStatus)。
*/
/** 会话 processing 旧 status_label → 统一 ShippingProcessingStatus。 */
const LEGACY_STATUS_TO_PROCESSING: Record<string, string> = {
queued: 'processing',
processing: 'processing',
pending_review: 'waiting_review',
waiting_review: 'waiting_review',
failed: 'failed',
completed: 'completed',
cancelled: 'cancelled',
cancelling: 'processing',
blocked: 'blocked',
automating: 'automating',
};
/**
* 解析统一处理状态的展示文案键。
* 核心逻辑:优先 `chat.shippingProcessing.status.<code>`。
* @param status - ShippingProcessingStatus 码
* @returns i18n key
*/
export function shippingProcessingStatusKey(status: string): string {
const code = String(status || '').trim();
const mapped = LEGACY_STATUS_TO_PROCESSING[code] || code;
return mapped
? `chat.shippingProcessing.status.${mapped}`
: 'chat.shippingProcessing.status.processing';
}
/**
* 解析任务状态展示文案。
*
* @param code - 后端 status / status_label
* @param te - i18n te
* @param t - i18n t
* @returns 本地化文案;皆无则回退原码
*/
export function resolveShippingProcessingStatusLabel(
code: string,
te: (key: string) => boolean,
t: (key: string) => string,
): string {
const raw = String(code || '').trim();
if (!raw) return '—';
const processingKey = shippingProcessingStatusKey(raw);
if (te(processingKey)) return t(processingKey);
const taskStatusKey = `chat.shippingProcessing.taskStatus.${raw}`;
if (te(taskStatusKey)) return t(taskStatusKey);
return raw;
}
/**
* 解析统一处理文案。
*
* @param leaf - 文案叶子键(如 groupNeedsAction)
* @param te - i18n te
* @param t - i18n t
* @param params - 插值参数
* @returns 本地化文案
*/
export function resolveShippingProcessingMessage(
leaf: string,
te: (key: string) => boolean,
t: (key: string, params?: Record<string, unknown>) => string,
params?: Record<string, unknown>,
): string {
const code = String(leaf || '').trim();
if (!code) return '';
const primary = `chat.shippingProcessing.${code}`;
if (te(primary)) return t(primary, params);
return code;
}
/**
* 解析统一处理阶段的展示文案键。
* @param stage - ShippingProcessingStage 码
* @returns i18n key
*/
export function shippingProcessingStageKey(stage: string): string {
const code = String(stage || '').trim();
return code
? `chat.shippingProcessing.stage.${code}`
: 'chat.shippingProcessing.stage.upload_received';
}
/**
* 解析工作项类型文案键。
* @param workItemType - order_intake | order_task
* @returns i18n key
*/
export function shippingProcessingWorkItemTypeKey(workItemType: string): string {
const code = String(workItemType || '').trim();
return code
? `chat.shippingProcessing.workItemType.${code}`
: 'chat.shippingProcessing.workItemType.order_task';
}
/**
* 解析来源类型文案键(eml / direct_pdf)。
* @param sourceType - OrderIntakeSourceType
* @returns i18n key
*/
export function shippingProcessingSourceTypeKey(sourceType: string): string {
const code = String(sourceType || '').trim();
return code
? `chat.shippingProcessing.sourceType.${code}`
: 'chat.shippingProcessing.sourceType.eml';
}
@@ -5,7 +5,10 @@
* 逻辑:后端 UI State 缺失时,前端仍需把关键人工介入态渲染为 blocked。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingWorkflowSteps } from './shippingStepper';
import {
applyShippingProcessingStageToSteps,
buildShippingWorkflowSteps,
} from './shippingStepper';
describe('shippingStepper', () => {
it('marks inventory step as blocked when RPA inventory is exhausted', () => {
@@ -29,4 +32,19 @@ describe('shippingStepper', () => {
expect(steps[2]?.status).toBe('blocked');
});
it('overlays unified processing stage onto base stepper steps', () => {
const base = buildShippingWorkflowSteps({
process_status: 'parsed',
current_step: 'step2_parse_confirm',
});
const overlaid = applyShippingProcessingStageToSteps(base, {
status: 'waiting_review',
stage: 'waiting_review',
currentGate: { status: 'blocked' },
});
// 关键断言:统一投影 waiting_review 应把第 2 步标为 blocked,而非沿用旧 process_status。
expect(overlaid[1]?.status).toBe('blocked');
expect(overlaid[0]?.status).toBe('completed');
});
});
@@ -1,9 +1,15 @@
/**
* features/chat/shipping/shippingStepper.ts
* 用途:基于 shipping task 状态推导前端七步 Stepper 展示数据。
* 依赖:无外部模块;ShippingWorkflowStepper.vue 消费本模块输出。
* 逻辑:buildShippingWorkflowSteps 将 process_status / checkpoint 等映射为步骤 id 与 done/active 状态。
* 用途:基于 shipping task 状态推导前端 Stepper 展示数据(七步 legacy / 四步履约)。
* 依赖:ShippingProcessingProjection(可选叠加)、shippingProcessingFulfillment;ShippingWorkflowStepper.vue 消费输出。
* 逻辑:任务台优先 buildFulfillmentWorkflowSteps(四节点);无投影时不回退旧 ui_state;
* resolveShippingWorkflowSteps 仍供对话等未切流页面作 legacy 回退。
*/
import {
FULFILLMENT_PROGRESS_NODES,
fulfillmentNodeIndexFromStage,
type FulfillmentProgressNodeKey,
} from './shippingProcessingFulfillment';
export interface ShippingTaskStepperSource {
process_status?: string | null;
review_status?: string | null;
@@ -135,6 +141,64 @@ function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined):
return 0;
}
/** 统一 ShippingProcessingStage → 粗粒度 Stepper 下标(过渡期;阶段 2 换 UnifiedProgressTrack)。 */
const PROCESSING_STAGE_INDEX_MAP: Record<string, number> = {
upload_received: 0,
email_parsing: 1,
document_parsing: 1,
email_adjudicating: 1,
candidate_creating: 1,
customer_resolving: 1,
duplicate_checking: 1,
// 业务 15 阶中库存源在复核前;七步 legacy 仍映射到「库存准备」步。
inventory_source_resolving: 2,
waiting_review: 1,
order_creating: 1,
inventory_fetching: 2,
inventory_matching: 4,
excel_generating: 5,
freight_uploading: 6,
completed: 6,
};
/**
* 用统一投影 stage/status 覆盖 Stepper 当前步(切流主源)。
*
* 核心逻辑:有投影时按 stage 重算 completed/current/pending;blocked/failed 标当前步 blocked;
* 无投影或无法映射时原样返回 baseSteps。
*
* @param baseSteps - ui_state / process_status 推导的步骤
* @param projection - 统一 order_task 投影
*/
export function applyShippingProcessingStageToSteps(
baseSteps: ShippingWorkflowStepItem[],
projection: { status?: string | null; stage?: string | null; currentGate?: { status?: string | null } | null } | null | undefined,
): ShippingWorkflowStepItem[] {
if (!projection || !baseSteps.length) return baseSteps;
const stage = String(projection.stage || '').trim();
const status = String(projection.status || '').trim().toLowerCase();
const stageIndex = PROCESSING_STAGE_INDEX_MAP[stage];
if (stageIndex === undefined && status !== 'completed' && status !== 'failed' && status !== 'blocked') {
return baseSteps;
}
const currentIndex = status === 'completed' ? baseSteps.length - 1 : (stageIndex ?? 0);
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|| status === 'blocked'
|| status === 'failed'
|| status === 'waiting_review';
return baseSteps.map((step, index) => {
let nextStatus: ShippingWorkflowStepItem['status'] = 'pending';
if (status === 'completed' || status === 'cancelled') {
nextStatus = 'completed';
} else if (index < currentIndex) {
nextStatus = 'completed';
} else if (index === currentIndex) {
nextStatus = gateBlocked ? 'blocked' : 'current';
}
return { ...step, status: nextStatus };
});
}
/**
* 将 task 状态映射为七步 Stepper 项(id / label / done / active)。
*/
@@ -178,3 +242,45 @@ export function buildShippingWorkflowSteps(
};
});
}
/**
* 从统一 ShippingProcessing 投影构建履约四节点 Stepper(任务台主源)。
*
* 核心逻辑:仅在有投影时返回步骤;节点标签由调用方传入 i18n 文案。
*
* @param projection - 统一 order_task 投影
* @param nodeLabels - 四节点展示文案(building_order … freight_uploading)
* @returns 四步 Stepper 项;无投影时返回 null
*/
export function buildFulfillmentWorkflowSteps(
projection: {
stage?: string | null;
status?: string | null;
currentGate?: { status?: string | null } | null;
} | null | undefined,
nodeLabels: Record<FulfillmentProgressNodeKey, string>,
): ShippingWorkflowStepItem[] | null {
if (!projection) return null;
const activeIndex = fulfillmentNodeIndexFromStage(projection.stage, projection.status);
const status = String(projection.status || '').trim().toLowerCase();
const gateBlocked = String(projection.currentGate?.status || '').trim().toLowerCase() === 'blocked'
|| status === 'blocked'
|| status === 'failed'
|| status === 'waiting_review';
return FULFILLMENT_PROGRESS_NODES.map((key, index) => {
let stepStatus: ShippingWorkflowStepItem['status'] = 'pending';
if (status === 'completed' || status === 'cancelled') {
stepStatus = 'completed';
} else if (activeIndex >= 0 && index < activeIndex) {
stepStatus = 'completed';
} else if (activeIndex >= 0 && index === activeIndex) {
stepStatus = gateBlocked ? 'blocked' : 'current';
}
return {
id: `fulfillment-${key}`,
label: nodeLabels[key as FulfillmentProgressNodeKey],
status: stepStatus,
};
});
}
@@ -0,0 +1,42 @@
/**
* features/chat/shipping/shippingSubmissionFeedback.spec.ts
* 用途:验收统一提交决策反馈结构(无弹窗、含短时标签码)。
* 依赖:Vitest、shippingSubmissionFeedback。
*/
import { describe, expect, it } from 'vitest';
import {
buildShippingSubmissionFeedback,
createComposerContextId,
createShippingSubmissionId,
} from './shippingSubmissionFeedback';
describe('shippingSubmissionFeedback', () => {
it('maps appended / created decisions to badge codes', () => {
expect(buildShippingSubmissionFeedback({
decision: 'appended',
user_task_no: 'OT-1',
run_no: 'RUN-1',
created_new: false,
}, 3)).toMatchObject({
decision: 'appended',
badgeCode: 'just_appended',
fileCount: 3,
recentAppendCount: 3,
});
expect(buildShippingSubmissionFeedback({
decision: 'created',
user_task_no: 'OT-2',
run_no: 'RUN-2',
created_new: true,
}, 1)).toMatchObject({
decision: 'created',
badgeCode: 'just_created',
createdNew: true,
});
});
it('creates stable-looking submission and composer ids', () => {
expect(createShippingSubmissionId()).toMatch(/^SUB-/);
expect(createComposerContextId()).toMatch(/^CMP-/);
});
});
@@ -0,0 +1,63 @@
/**
* features/chat/shipping/shippingSubmissionFeedback.ts
* 用途:根据统一提交决策生成聊天区非阻塞系统文案与右侧短时标签。
* 依赖:OrderExtractionSubmissionResponse;不含敏感数据。
* 逻辑:由 useShippingOrderExtractionRuns / ChatMessageBubble 消费;不弹窗、不作为唯一 Toast。
*/
import type { OrderExtractionSubmissionResponse } from '@/features/chat/types/shipping.api.types';
export interface ShippingSubmissionFeedback {
/** 聊天区可回看系统消息正文(调用方再走 i18n 模板时也可只用 decision) */
decision: 'appended' | 'created';
fileCount: number;
userTaskNo: string;
runNo: string;
createdNew: boolean;
reasonCode?: string | null;
/** 右侧任务卡短时标签码 */
badgeCode: 'just_appended' | 'just_created';
recentAppendCount?: number;
}
/**
* 从提交响应生成用户可见反馈结构。
* @param response - 统一提交 API 响应
* @param fileCount - 本次发送附件数
*/
export function buildShippingSubmissionFeedback(
response: OrderExtractionSubmissionResponse,
fileCount: number,
): ShippingSubmissionFeedback {
const decision = response.decision === 'appended' ? 'appended' : 'created';
return {
decision,
fileCount: Math.max(0, Number(fileCount) || 0),
userTaskNo: String(response.user_task_no || '').trim(),
runNo: String(response.run_no || '').trim(),
createdNew: Boolean(response.created_new),
reasonCode: response.reason_code ?? null,
badgeCode: decision === 'appended' ? 'just_appended' : 'just_created',
recentAppendCount: decision === 'appended' ? Math.max(0, Number(fileCount) || 0) : undefined,
};
}
/**
* 生成稳定 submission_id(同一次发送重试用同一 id)。
*/
export function createShippingSubmissionId(): string {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `SUB-${globalThis.crypto.randomUUID()}`;
}
return `SUB-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
/**
* 生成输入区短生命周期 composer_context_id。
*/
export function createComposerContextId(): string {
if (typeof globalThis.crypto?.randomUUID === 'function') {
return `CMP-${globalThis.crypto.randomUUID()}`;
}
return `CMP-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
@@ -1,43 +1,24 @@
/**
* features/chat/shipping/shippingTurnActions.spec.ts
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
* 用途:验证决策/冻结等 Chat Turn 映射(不含已下线的 create_batch)。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn, resolveShippingChatTurn } from './shippingTurnActions';
import { resolveShippingChatTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
const files = [
new File(['notice-a'], 'notice-a.txt', { type: 'text/plain' }),
new File(['notice-b'], 'notice-b.txt', { type: 'text/plain' }),
];
const turn = buildShippingCreateBatchTurn(files, 'conv-001', 'idem-key-001');
expect(turn.actionType).toBe('shipping.create_batch_from_notices');
expect(turn.payload.conversation_id).toBe('conv-001');
expect(turn.payload.file_count).toBe(2);
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
it('buildShippingCreateBatchFromIntakesTurn includes selected candidate_nos', () => {
const turn = buildShippingCreateBatchFromIntakesTurn(
['SNI-001'],
'conv-001',
'idem-candidate-001',
['SNC-001', 'SNC-003'],
);
expect(turn.actionType).toBe('shipping.create_batch_from_intakes');
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
});
it('maps freeze_order only with the version shown to the user', () => {
// 关键断言:缺版本不得构造 freeze Turn,避免乐观锁盲写。
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
});
});
it('maps confirm decision to submit_decision', () => {
expect(resolveShippingChatTurn('confirm', 'sn-1')).toEqual({
actionType: 'shipping.submit_decision',
payload: { task_no: 'SN-1', decision: 'confirm' },
});
});
});
@@ -2,7 +2,8 @@
* features/chat/shipping/shippingTurnActions.ts
* 用途:将发货通知菜单/决策 action.id 映射为 Chat Turn action_type + payload。
* 依赖:constants/shipping。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息。
* 逻辑:useChatShippingDecision 与 useChatShippingMenuHandler 调用本模块,不再直调 workspace API 插消息;
* co8 后已移除 create_batch / switch_batch_focus Turn 构造器,上传改走 Intake + order extraction。
*/
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
@@ -82,55 +83,6 @@ export function buildShippingSubmitDecisionTurn(
},
};
}
/**
* 构造发货通知建批 Chat Turn(multipart 上传)。
*/
export function buildShippingCreateBatchTurn(
files: File[],
conversationId?: string | null,
idempotencyKey?: string,
): { actionType: string; displayText: string; payload: Record<string, unknown>; files: File[] } {
const count = files.length;
const displayText = count === 1
? `上传发货通知:${files[0]?.name || '附件'}`
: `上传 ${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_notices',
displayText,
payload: {
conversation_id: conversationId || undefined,
file_count: count,
idempotency_key: idempotencyKey,
},
files,
};
}
/**
* 构造发货通知建批 Chat Turn(基于已解析 intake,不再携带 files)。
*/
export function buildShippingCreateBatchFromIntakesTurn(
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
const count = intakeNos.length;
const displayText = count === 1
? `确认建单:${intakeNos[0]}`
: `确认建单:${count} 份发货通知`;
return {
actionType: 'shipping.create_batch_from_intakes',
displayText,
payload: {
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
},
};
}
/**
* 构造货代领域 refs,键名与 agent_runtime_context.refs 对齐。
*/
@@ -143,6 +95,9 @@ export function buildShippingTurnRefs(taskNo: string, batchNo?: string): Record<
return refs;
}
/**
* 构造重新上传发货通知 Chat Turn。
*/
export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
const task = String(taskNo || '').trim().toUpperCase();
return {
@@ -154,17 +109,9 @@ export function buildShippingReplaceNoticeTurn(taskNo: string, file: File) {
};
}
export function buildShippingSwitchFocusTurn(batchNo: string, taskNo: string, displayText: string) {
const batch = String(batchNo || '').trim();
const task = String(taskNo || '').trim().toUpperCase();
return {
actionType: 'shipping.switch_batch_focus',
displayText,
payload: { batch_no: batch, task_no: task },
refs: buildShippingTurnRefs(task, batch),
};
}
/**
* 构造短缺明细查询 Chat Turn。
*/
export function buildShippingQueryShortageTurn(taskNo: string, displayText: string) {
const task = String(taskNo || '').trim().toUpperCase();
return {
@@ -251,4 +251,17 @@ describe('useChatShippingSendHandler', () => {
expect(attachments.value).toEqual([attachment]);
expect(ctx.msg.warning).toHaveBeenCalledWith('run create failed');
});
it('warns and consumes send when user tries batch task switching (co8 batch API retired)', async () => {
const ctx = createContext({
getActiveShippingBatchNo: () => 'SB-TEST',
});
const { tryHandleShippingSend } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingSend(undefined, '下一票', '下一票');
expect(consumed).toBe(true);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
expect(ctx.msg.warning).toHaveBeenCalledWith('chat.shippingNoticeUi.batchSwitchRemoved');
});
});
@@ -1,15 +1,13 @@
/**
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;其他业务动作经 Chat Turn / handleShippingMenuAction。
* 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。
* 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。
*/
import {
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { buildShippingSwitchFocusTurn } from './shippingTurnActions';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import {
isShippingDownloadExcelIntent,
@@ -146,58 +144,17 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
};
/**
* 拦截切票/切任务意图(co8 已下线批次 API)。
*
* 核心逻辑:识别切换意图后提示用户使用右侧 processing 工作台,消费发送且不发起网络请求。
* @param content - 用户输入
* @returns 识别到切换意图时恒为 true
*/
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
const intent = parseShippingTaskSwitchIntent(content);
if (!intent) return false;
const batchNo = ctx.getActiveShippingBatchNo();
if (!batchNo) {
ctx.msg.warning('当前没有可切换的批次');
return true;
}
try {
const detail = await getWorkspaceShippingBatch(batchNo);
const tasks = Array.isArray(detail.tasks) ? detail.tasks : [];
if (tasks.length <= 1) {
ctx.msg.info('当前批次只有 1 票,无需切换');
return true;
}
const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase();
const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0);
let targetTaskNo = '';
if (intent.mode === 'task') {
targetTaskNo = String(intent.taskNo || '').trim().toUpperCase();
} else if (intent.mode === 'next') {
targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase();
} else {
targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase();
}
if (!targetTaskNo) {
ctx.msg.warning('未找到要切换的任务');
return true;
}
if (targetTaskNo === focusTaskNo) {
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
return true;
}
ctx.resolvedShippingTaskId.value = targetTaskNo;
const turn = buildShippingSwitchFocusTurn(batchNo, targetTaskNo, content.trim());
await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
refs: turn.refs,
hooks: {
onAssistantMessageFinished: async () => {
void ctx.refreshShippingActions();
},
},
});
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
ctx.msg.warning(errorMessage);
}
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.batchSwitchRemoved'));
return true;
};
@@ -293,10 +250,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
}
if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false;
if (!trimmed || requestedAutoFlow) {
// co8:本地文件改走 Intake 入队,不再清空后打 create_batch Chat Turn。
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
try {
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
ctx.attachments.value = ctx.attachments.value.filter((item) => item.kind !== 'local');
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
@@ -2,7 +2,7 @@
* features/chat/shipping/useChatShippingUploadHandler.spec.ts
* 用途:验证发货通知上传 handler 在显式 taskId 场景下不会把库存/通知文件错投到当前激活任务。
* 依赖:vitest、vue refs、shipping.api、useChatShippingUploadHandler。
* 逻辑:覆盖库存/通知 picker 的任务锁定,以及 Chat Turn 建批/覆盖路径。
* 逻辑:覆盖库存/通知 picker 的任务锁定、replace_notice Turn,以及 Intake/OT 提交路径。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -55,8 +55,10 @@ const createContext = (
getActiveShippingTaskId: () => 'SN-ACTIVE-001',
startChatTurn: vi.fn(async () => true),
refreshShippingActions: vi.fn(async () => undefined),
msg: { warning: vi.fn() },
msg: { warning: vi.fn(), info: vi.fn() },
t: (key: string) => key,
enqueueNoticeFiles: vi.fn(async () => undefined),
startOrderExtractionRun: vi.fn(async () => true),
sendTemporaryInventoryMessage: vi.fn(async () => undefined),
...overrides,
});
@@ -148,33 +150,50 @@ describe('useChatShippingUploadHandler', () => {
expect(ctx.pendingShippingNoticeTaskId.value).toBe('');
});
it('creates notice batch via Chat Turn instead of local assistant push', async () => {
it('enqueues notice files as intakes instead of create_batch Chat Turn', async () => {
const enqueueNoticeFiles = vi.fn(async () => undefined);
const ctx = createContext({
getActiveShippingTaskId: () => '',
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
expect(ctx.startChatTurn).toHaveBeenCalledWith(
expect.objectContaining({
inputType: 'upload_followup',
actionType: 'shipping.create_batch_from_notices',
displayText: expect.stringContaining('notice.pdf'),
files: [file],
}),
);
expect(enqueueNoticeFiles).toHaveBeenCalledWith([file]);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('double click only calls startChatTurn once and keeps stable idempotency key', async () => {
const startChatTurn = vi.fn(async () => {
it('submits parsed intakes via order extraction instead of create_batch_from_intakes', async () => {
const startOrderExtractionRun = vi.fn(async () => true);
const clearConsumedNoticeAttachments = vi.fn();
const ctx = createContext({
getActiveShippingTaskId: () => '',
getParsedIntakeNos: () => ['SNI-1'],
startOrderExtractionRun,
clearConsumedNoticeAttachments,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
await handleShippingAutoUploadNoticeBatch([]);
expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage',
['SNI-1'],
[],
);
expect(clearConsumedNoticeAttachments).toHaveBeenCalled();
expect(ctx.startChatTurn).not.toHaveBeenCalled();
});
it('double click only enqueues notice files once', async () => {
const enqueueNoticeFiles = vi.fn(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
return true;
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
@@ -183,168 +202,30 @@ describe('useChatShippingUploadHandler', () => {
const second = handleShippingAutoUploadNoticeBatch([file]);
await Promise.all([first, second]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
const payload = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload;
expect(payload?.idempotency_key).toBeTruthy();
expect(enqueueNoticeFiles).toHaveBeenCalledTimes(1);
});
it('reuses idempotency key on retry and generates new key after success', async () => {
let attempt = 0;
const startChatTurn = vi.fn(async () => {
attempt += 1;
return attempt >= 2;
it('releases submit lock when enqueueNoticeFiles fails', async () => {
const enqueueNoticeFiles = vi.fn(async () => {
throw new Error('enqueue failed');
});
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const thirdKey = (startChatTurn.mock.calls[2]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBe(secondKey);
expect(thirdKey).not.toBe(secondKey);
});
it('generates new idempotency key when files change after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const firstFile = new File(['notice-a'], 'notice-a.pdf', { type: 'application/pdf' });
const secondFile = new File(['notice-b'], 'notice-b.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([firstFile]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([secondFile]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('reuses idempotency key when conversation upgrades from empty to server-assigned after network failure', async () => {
const conversationId = ref<string | null>(null);
const startChatTurn = vi.fn(async () => {
conversationId.value = 'conv-server-new';
return false;
});
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBe(firstKey);
});
it('generates new idempotency key when switching from new chat to historical session', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref<string | null>(null);
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-history', '');
conversationId.value = 'conv-history';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key after explicit clearPendingNoticeBatchRetry', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
clearPendingNoticeBatchRetry();
conversationId.value = null;
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('generates new idempotency key when conversation changes after a failed attempt', async () => {
const startChatTurn = vi.fn(async () => false);
const conversationId = ref('conv-a');
const ctx = createContext({
conversationId,
getActiveShippingTaskId: () => '',
startChatTurn,
});
const { handleShippingAutoUploadNoticeBatch } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await handleShippingAutoUploadNoticeBatch([file]);
const firstKey = (startChatTurn.mock.calls[0]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
onNoticeBatchConversationChanging('conv-b', 'conv-a');
conversationId.value = 'conv-b';
await handleShippingAutoUploadNoticeBatch([file]);
const secondKey = (startChatTurn.mock.calls[1]?.[0] as { payload?: Record<string, unknown> })?.payload?.idempotency_key;
expect(firstKey).toBeTruthy();
expect(secondKey).toBeTruthy();
expect(secondKey).not.toBe(firstKey);
});
it('releases submit lock when fingerprint computation fails', async () => {
computeNoticeFilesContentFingerprint.mockRejectedValueOnce(new Error('digest failed'));
const startChatTurn = vi.fn(async () => true);
const ctx = createContext({
getActiveShippingTaskId: () => '',
startChatTurn,
enqueueNoticeFiles,
});
const { handleShippingAutoUploadNoticeBatch, isShippingNoticeBatchSubmitting } = createShippingUploadHandlers(ctx);
const file = new File(['notice'], 'notice.pdf', { type: 'application/pdf' });
await expect(handleShippingAutoUploadNoticeBatch([file])).rejects.toThrow('digest failed');
expect(startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
computeNoticeFilesContentFingerprint.mockResolvedValueOnce('fp-notice');
await handleShippingAutoUploadNoticeBatch([file]);
expect(startChatTurn).toHaveBeenCalledTimes(1);
expect(ctx.startChatTurn).not.toHaveBeenCalled();
expect(isShippingNoticeBatchSubmitting()).toBe(false);
expect(ctx.msg.warning).toHaveBeenCalled();
});
it('compatibility hooks for pending batch retry remain callable after co8', () => {
clearPendingNoticeBatchRetry();
onNoticeBatchConversationChanging('conv-b', 'conv-a');
expect(true).toBe(true);
});
it('does not open notice picker when both explicit taskId and active task are missing', () => {
@@ -1,83 +1,39 @@
/**
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 用途:处理发货通知与库存文件上传、订单抽取提交和附件建议提示。
* 依赖:shipping.api、file-assets.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:发货通知建批和单票覆盖经 Chat Turn;对话上传库存文件先成为私有临时资产,再进入 Dify 受控分析分支。
* 逻辑:co8 后不再走 shipping_batches Chat Turn;新通知经 enqueueNoticeFiles / startOrderExtractionRun;
* 单票覆盖仍经 replace_notice Turn;库存文件先成为私有临时资产再进 Dify 分析分支。
*/
import { computed } from 'vue';
import type { ShippingTaskSummary } from '@/features/chat/api/shipping.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { extractExt } from '../constants/shipping';
import { buildShippingCreateBatchTurn, buildShippingCreateBatchFromIntakesTurn, buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { computeNoticeFilesContentFingerprint, computeNoticeIntakeNosFingerprint } from './shippingNoticeBatchIdempotency';
import { buildShippingReplaceNoticeTurn, buildShippingTurnRefs } from './shippingTurnActions';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage } from '../types/chat.types';
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
import type { PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
let noticeBatchSubmitting = false;
interface PendingNoticeBatchRetryState {
conversationId: string;
idempotencyKey: string;
fileFingerprint: string;
}
let pendingNoticeBatchRetry: PendingNoticeBatchRetryState | null = null;
function normalizeConversationId(conversationId: string | null | undefined): string {
return String(conversationId || '').trim();
}
function clearPendingNoticeBatchRetryState(): void {
pendingNoticeBatchRetry = null;
}
/**
* 显式清理待重试建批幂等状态(新建聊天、切换 Agent 等不经 onConversationIdChanging 的路径)。
* 显式清理待重试建批幂等状态(co8 后建批已下线,保留空实现供会话切换调用方兼容)。
*/
export function clearPendingNoticeBatchRetry(): void {
clearPendingNoticeBatchRetryState();
/* no-op: shipping_batches 已 DROP */
}
/**
* 判断待重试状态是否应绑定到当前会话。
* 核心逻辑:允许「尚未分配会话」升级绑定服务端新 ID;两个非空且不同、或旧非空而新为空时清理。
*/
function reconcilePendingNoticeBatchConversation(
pending: PendingNoticeBatchRetryState,
conversationKey: string,
): void {
const pendingKey = pending.conversationId;
if (pendingKey === conversationKey) {
return;
}
if (!pendingKey && conversationKey) {
pending.conversationId = conversationKey;
return;
}
if (pendingKey && !conversationKey) {
clearPendingNoticeBatchRetryState();
return;
}
if (pendingKey && conversationKey && pendingKey !== conversationKey) {
clearPendingNoticeBatchRetryState();
}
}
/**
* 用户主动切换会话时清理待重试建批状态,避免跨会话复用幂等键。
* 仅由 onConversationIdChanging 调用;SSE 自动分配 conversation_id 不经过此函数。
* 用户主动切换会话时的钩子(co8 后无幂等键可清)。
* @param _nextId - 新会话 ID
* @param _prevId - 旧会话 ID
*/
export function onNoticeBatchConversationChanging(
nextId: string,
prevId?: string | null,
_nextId: string,
_prevId?: string | null,
): void {
const next = normalizeConversationId(nextId);
const prev = normalizeConversationId(prevId);
if (next !== prev) {
clearPendingNoticeBatchRetryState();
}
/* no-op */
}
/**
@@ -113,11 +69,20 @@ export interface ShippingUploadHandlerContext {
getActiveShippingTaskId: () => string;
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
msg: { warning: (text: string) => void; info?: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
getSelectedCandidateNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
/** 将本地文件加入输入栏并创建 Intake(替代旧 create_batch_from_notices)。 */
enqueueNoticeFiles?: (files: File[]) => Promise<void>;
/** 对已解析 Intake 发起订单抽取提交。 */
startOrderExtractionRun?: (
query: string,
intakeNos: string[],
attachments: ChatMessageAttachment[],
uploadBatchId?: string,
) => Promise<boolean>;
sendTemporaryInventoryMessage: (assetNo: string, fileName: string) => Promise<unknown>;
}
@@ -202,56 +167,28 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
};
/**
* 将本地通知文件加入输入栏并创建 Intake(不再走 shipping_batches Chat Turn)。
* @param files - 用户选择的发货通知文件
* @returns 是否完成入队
*/
const runNoticeBatchChatTurn = async (files: File[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const fileFingerprint = await computeNoticeFilesContentFingerprint(files);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== fileFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = fileFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchTurn(files, ctx.conversationId.value, idempotencyKey);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
files: turn.files,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
} else {
if (!ctx.enqueueNoticeFiles) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
return ok;
await ctx.enqueueNoticeFiles(files);
ctx.msg.info?.(ctx.t('chat.shippingNoticeWaitingForParse'));
void ctx.refreshShippingActions();
return true;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
@@ -278,61 +215,34 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
const runNoticeBatchFromIntakes = async (intakeNos: string[], candidateNos: string[]) => {
/**
* 对已解析 Intake 发起订单抽取提交(替代 create_batch_from_intakes)。
* @param intakeNos - 已解析 Intake 编号
* @param _candidateNos - 保留签名;候选选择由提交服务侧裁决
* @returns 是否提交成功
*/
const runNoticeBatchFromIntakes = async (intakeNos: string[], _candidateNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const intakeFingerprint = computeNoticeIntakeNosFingerprint([...intakeNos, ...candidateNos]);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
if (!ctx.startOrderExtractionRun) {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
}
if (
pendingNoticeBatchRetry
&& pendingNoticeBatchRetry.fileFingerprint !== intakeFingerprint
) {
clearPendingNoticeBatchRetryState();
}
if (!pendingNoticeBatchRetry) {
pendingNoticeBatchRetry = {
conversationId: conversationKey,
idempotencyKey: crypto.randomUUID(),
fileFingerprint: intakeFingerprint,
};
} else {
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchFromIntakesTurn(
intakeNos,
ctx.conversationId.value,
idempotencyKey,
candidateNos,
);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
displayText: turn.displayText,
actionType: turn.actionType,
payload: turn.payload,
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
syncBatchContextFromTurnMessage(assistantMsg);
void ctx.refreshShippingActions();
},
},
});
const query = ctx.input.value.trim() || ctx.t('chat.shippingOrderExtractionDefaultUserMessage');
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
if (ok) {
if (pendingNoticeBatchRetry?.conversationId === conversationKey) {
clearPendingNoticeBatchRetryState();
}
ctx.clearConsumedNoticeAttachments?.();
void ctx.refreshShippingActions();
} else {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
}
return ok;
} catch {
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false;
} finally {
noticeBatchSubmitting = false;
}
@@ -1,106 +1,120 @@
/**
* features/chat/shipping/useShippingNoticeWorkflow.spec.ts
* 用途:覆盖 Workflow 轮询退避、多批次选择、停轮询条件与取消/重识别后刷新。
* 用途:覆盖 ShippingProcessing 恢复、轮询退避与跨会话迟到响应隔离。
* 依赖:Vitest、vue、shipping.api mock。
* 逻辑:断言 backoff 封顶、终态停轮询、选中保留、cancelItem/reparseItem 调 API 后 refresh。
* 逻辑:co8 后仅验证统一 shipping-processing 读源与轮询策略;无 Workflow 空壳字段。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { nextTick, ref } from 'vue';
import {
resolveSelectedWorkflowNo,
resolveWorkflowPollBackoffMs,
shouldContinueWorkflowPolling,
resolveProcessingPollBackoffMs,
shouldContinueProcessingPolling,
useShippingNoticeWorkflow,
} from './useShippingNoticeWorkflow';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../types/shipping.api.types';
import type { ConversationProcessingProjection } from '../types/shipping.api.types';
const api = vi.hoisted(() => ({
listWorkflows: vi.fn(),
cancelItem: vi.fn(),
reparseItem: vi.fn(),
getShippingProcessing: vi.fn(async () => {
throw new Error('unified_unavailable');
}),
focusTask: vi.fn(),
markViewed: vi.fn(),
}));
vi.mock('../api/shipping.api', () => ({
listWorkspaceShippingWorkflows: api.listWorkflows,
cancelWorkspaceShippingWorkflowItem: api.cancelItem,
reparseWorkspaceShippingWorkflowItem: api.reparseItem,
getWorkspaceShippingProcessing: api.getShippingProcessing,
focusWorkspaceConversationTask: api.focusTask,
markWorkspaceConversationTaskViewed: api.markViewed,
}));
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
/**
* 构造历史会话右侧任务投影。
*/
function buildProcessing(conversationId = 'conv-1'): ConversationProcessingProjection {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'notice-a.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
conversation_id: conversationId,
summary: {
total_tasks: 1,
total_files: 2,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
processing: [],
needs_action: [{
user_task_no: `OT-${conversationId}`,
group: 'needs_action',
can_append: false,
file_count: 2,
}],
completed: [],
history: [],
};
}
function buildWorkflow(patch: Partial<ShippingWorkflow> = {}): ShippingWorkflow {
const items = patch.items ?? [buildItem()];
/**
* 构造统一 shipping-processing 响应(内嵌 conversation_processing)。
*/
function buildUnifiedProcessing(conversationId = 'conv-1') {
return {
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.length,
pending_review: 0,
failed: 0,
completed: 0,
},
items,
...patch,
conversation_id: conversationId,
work_items: [],
conversation_processing: buildProcessing(conversationId),
};
}
/**
* 创建可手动完成的 Promise。
*/
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, resolve, reject };
}
describe('useShippingNoticeWorkflow helpers', () => {
it('caps failure backoff at 8s', () => {
expect(resolveWorkflowPollBackoffMs(1)).toBe(2000);
expect(resolveWorkflowPollBackoffMs(2)).toBe(4000);
expect(resolveWorkflowPollBackoffMs(3)).toBe(8000);
expect(resolveWorkflowPollBackoffMs(10)).toBe(8000);
expect(resolveProcessingPollBackoffMs(1)).toBe(2000);
expect(resolveProcessingPollBackoffMs(2)).toBe(4000);
expect(resolveProcessingPollBackoffMs(3)).toBe(8000);
expect(resolveProcessingPollBackoffMs(10)).toBe(8000);
});
it('stops polling on terminal workflow status', () => {
const workflow = buildWorkflow({ status: 'completed' });
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
it('stops when processing idle', () => {
expect(shouldContinueProcessingPolling(null)).toBe(false);
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 0, processing: 0, needs_action: 0, history: 0 },
processing: [],
needs_action: [],
history: [],
})).toBe(false);
});
it('continues while layout_parsing items remain', () => {
const items = [buildItem({ lifecycle_status: 'layout_parsing' })];
const workflow = buildWorkflow({ status: 'open', items });
expect(shouldContinueWorkflowPolling([workflow])).toBe(true);
});
it('stops when open workflow has only closed items', () => {
const items = [buildItem({ lifecycle_status: 'closed' })];
const workflow = buildWorkflow({ status: 'open', items });
expect(shouldContinueWorkflowPolling([workflow])).toBe(false);
});
it('keeps previous selection when still present, else first', () => {
const a = buildWorkflow({ workflow_no: 'SNWF-A' });
const b = buildWorkflow({ workflow_no: 'SNWF-B' });
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-B')).toBe('SNWF-B');
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-GONE')).toBe('SNWF-A');
expect(resolveSelectedWorkflowNo([a, b], 'SNWF-A', 'SNWF-B')).toBe('SNWF-B');
it('continues when processing projection is active', () => {
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 1, processing: 1, needs_action: 0, history: 0 },
processing: [{
user_task_no: 'OT-1',
group: 'processing',
can_append: true,
}],
needs_action: [],
history: [],
})).toBe(true);
});
});
describe('useShippingNoticeWorkflow', () => {
beforeEach(() => {
api.listWorkflows.mockReset();
api.cancelItem.mockReset();
api.reparseItem.mockReset();
api.getShippingProcessing.mockReset();
api.getShippingProcessing.mockRejectedValue(new Error('unified_unavailable'));
api.focusTask.mockReset();
api.markViewed.mockReset();
vi.useFakeTimers();
});
@@ -108,20 +122,8 @@ describe('useShippingNoticeWorkflow', () => {
vi.useRealTimers();
});
it('loads open workflow items and exposes cancelItem refresh', async () => {
const workflow = buildWorkflow({
items: [
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
],
});
api.listWorkflows.mockResolvedValue({
conversation_id: 'conv-1',
workflows: [workflow],
});
api.cancelItem.mockResolvedValue({
item: buildItem({ item_no: 'SWI-A', lifecycle_status: 'cancelled' }),
});
it('loads processing projection without workflow shells', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
@@ -129,67 +131,15 @@ describe('useShippingNoticeWorkflow', () => {
await nextTick();
await Promise.resolve();
expect(api.listWorkflows).toHaveBeenCalled();
expect(ctl.items.value.map((row) => row.item_no)).toEqual(['SWI-A', 'SWI-B']);
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
await ctl.cancelItem('SWI-A', { reason: 'user cancel', expected_lock_version: 1 });
expect(api.cancelItem).toHaveBeenCalledWith('SWI-A', {
reason: 'user cancel',
expected_lock_version: 1,
});
expect(api.listWorkflows.mock.calls.length).toBeGreaterThanOrEqual(2);
ctl.stop();
});
it('selects among multiple workflows and reparses', async () => {
const first = buildWorkflow({
workflow_no: 'SNWF-1',
items: [buildItem({ item_no: 'SWI-1', workflow_no: 'SNWF-1' })],
});
const second = buildWorkflow({
workflow_no: 'SNWF-2',
items: [
buildItem({
item_no: 'SWI-2',
workflow_no: 'SNWF-2',
lifecycle_status: 'failed',
current_document_filename: 'fail.pdf',
}),
],
});
api.listWorkflows.mockResolvedValue({
conversation_id: 'conv-1',
workflows: [first, second],
});
api.reparseItem.mockResolvedValue({
item: buildItem({ item_no: 'SWI-2', lifecycle_status: 'extracting' }),
});
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.workflows.value).toHaveLength(2);
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-1');
ctl.selectWorkflow('SNWF-2');
expect(ctl.selectedWorkflowNo.value).toBe('SNWF-2');
expect(ctl.items.value[0]?.item_no).toBe('SWI-2');
await ctl.reparseItem('SWI-2', { reason: 'retry', comment: 'note' });
expect(api.reparseItem).toHaveBeenCalledWith('SWI-2', {
reason: 'retry',
comment: 'note',
});
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processingWorkItems.value).toEqual([]);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('records recoverable error without throwing', async () => {
api.listWorkflows.mockRejectedValue(new Error('network down'));
const conversationId = ref('conv-1');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
@@ -198,4 +148,200 @@ describe('useShippingNoticeWorkflow', () => {
expect(ctl.error.value).toBe('network_recoverable');
ctl.stop();
});
it('restores processing tasks from unified shipping-processing', async () => {
api.getShippingProcessing.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value?.summary.needs_action).toBe(1);
expect(ctl.processing.value?.summary.total_files).toBe(2);
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('uses unified work_items as the sole processing read source', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [{
workItemType: 'order_task',
workItemNo: 'OT-UNIFIED',
sourceType: 'direct_pdf',
rootOrderTaskNo: 'OT-UNIFIED',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: {
gateCode: 'order_freeze_readiness',
status: 'blocked',
nextActionCode: 'open_order_review',
},
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'po.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-1',
},
childOrderTasks: [],
}],
conversation_processing: null,
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalled();
expect(ctl.processingWorkItems.value).toHaveLength(1);
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-UNIFIED');
ctl.stop();
});
it('derives sibling OT tasks from work_items when embedded conversation_processing omits them', async () => {
api.getShippingProcessing.mockResolvedValue({
conversation_id: 'conv-1',
work_items: [
{
workItemType: 'order_task',
workItemNo: 'OT-ROOT',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'waiting_review',
stage: 'waiting_review',
progressVersion: 1,
lastActivityAt: '2026-08-05T00:00:00Z',
currentGate: null,
availableActions: ['open_order_review'],
sourceSummary: {
emailSubject: null,
filename: 'root.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-ROOT',
},
childOrderTasks: [],
},
{
workItemType: 'order_task',
workItemNo: 'OT-SIBLING',
sourceType: 'eml',
rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null,
conversationId: 'conv-1',
submissionNo: 'SOS-1',
intakeNo: 'SNI-1',
status: 'processing',
stage: 'candidate_creating',
progressVersion: 1,
lastActivityAt: '2026-08-05T01:00:00Z',
currentGate: null,
availableActions: ['view_details'],
sourceSummary: {
emailSubject: null,
filename: 'sibling.pdf',
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-SIB',
},
childOrderTasks: [],
},
],
conversation_processing: {
summary: {
total_tasks: 1,
total_files: 1,
processing: 0,
needs_action: 1,
completed: 0,
history: 0,
},
focused_task_no: 'OT-ROOT',
recent_task_no: 'OT-SIBLING',
needs_action: [{
user_task_no: 'OT-ROOT',
group: 'needs_action',
can_append: false,
file_count: 1,
}],
processing: [],
completed: [],
history: [],
},
});
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
await Promise.resolve();
expect(ctl.processing.value?.needs_action.map((t) => t.user_task_no)).toEqual(['OT-ROOT']);
expect(ctl.processing.value?.processing.map((t) => t.user_task_no)).toEqual(['OT-SIBLING']);
expect(ctl.processing.value?.focused_task_no).toBe('OT-ROOT');
expect(ctl.processing.value?.recent_task_no).toBe('OT-SIBLING');
ctl.stop();
});
it('retries a failed initial processing restore instead of freezing at empty state', async () => {
api.getShippingProcessing
.mockRejectedValueOnce(new Error('temporary auth recovery'))
.mockResolvedValue(buildUnifiedProcessing());
const ctl = useShippingNoticeWorkflow({ conversationId: ref('conv-1') });
await vi.advanceTimersByTimeAsync(0);
await nextTick();
expect(ctl.error.value).toBe('network_recoverable');
await vi.advanceTimersByTimeAsync(2000);
await nextTick();
await Promise.resolve();
expect(api.getShippingProcessing).toHaveBeenCalledTimes(2);
expect(ctl.processing.value?.needs_action[0]?.user_task_no).toBe('OT-conv-1');
expect(ctl.error.value).toBeNull();
ctl.stop();
});
it('ignores an old conversation response that completes after the restored conversation', async () => {
const oldUnified = deferred<ReturnType<typeof buildUnifiedProcessing>>();
api.getShippingProcessing
.mockImplementationOnce(() => oldUnified.promise)
.mockResolvedValueOnce(buildUnifiedProcessing('conv-new'));
const conversationId = ref('conv-old');
const ctl = useShippingNoticeWorkflow({ conversationId });
await vi.advanceTimersByTimeAsync(0);
conversationId.value = 'conv-new';
await nextTick();
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
oldUnified.resolve(buildUnifiedProcessing('conv-old'));
await Promise.resolve();
await nextTick();
expect(ctl.processing.value?.conversation_id).toBe('conv-new');
ctl.stop();
});
});
@@ -1,10 +1,10 @@
/**
* features/chat/shipping/useShippingNoticeWorkflow.ts
* 用途:会话级 Shipping Notice Workflow 前台轮询、批次选择与取消/重识别编排。
* 依赖:shipping.api workflows / workflow-items、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;支持多批次 workflows[];
* 选中优先显式选择,否则保留仍在列表中的上一选,否则取首个;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;终态停轮询。
* 用途:会话级货代发货通知「本次处理」投影轮询(统一 ShippingProcessing)。
* 依赖:shipping.api getWorkspaceShippingProcessing / focus·viewed、Vue 响应式、BusinessError。
* 逻辑:由 ChatViewContent / ShippingWorkflowTimeline 消费;仅读 shipping-processing;
* focus/viewed 写路径优先应用响应中的 work_items;
* 前台 2s / 后台 8s;请求 10s AbortController 超时;失败指数退避至 8s;无活跃任务时停轮询。
*/
import {
computed,
@@ -19,37 +19,21 @@ import {
} from 'vue';
import { BusinessError } from '@/shared/api/client';
import {
cancelWorkspaceShippingWorkflowItem,
listWorkspaceShippingWorkflows,
reparseWorkspaceShippingWorkflowItem,
focusWorkspaceConversationTask,
getWorkspaceShippingProcessing,
markWorkspaceConversationTaskViewed,
} from '../api/shipping.api';
import type {
ShippingWorkflow,
ShippingWorkflowItem,
ConversationProcessingProjection,
ShippingProcessingProjection,
} from '../types/shipping.api.types';
import { resolveConversationProcessingFromUnified } from './conversationProcessingProjection';
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
const REQUEST_TIMEOUT_MS = 10000;
const MAX_BACKOFF_MS = 8000;
/** 仍需轮询的 Item 生命周期(含待人工上传登记;仅 closed/cancelled 为终态)。 */
const OPEN_ACTIVE_STATUSES = new Set([
'queued',
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
'pending_review',
'manual_upload_pending',
'reparse_failed',
'failed',
]);
/** Workflow 批次终态。 */
const TERMINAL_WORKFLOW_STATUSES = new Set(['completed', 'cancelled', 'failed']);
export type UseShippingNoticeWorkflowOptions = {
/** 当前会话 ID;空则停轮询并清空。 */
conversationId: MaybeRefOrGetter<string | null | undefined>;
@@ -58,27 +42,15 @@ export type UseShippingNoticeWorkflowOptions = {
};
export type UseShippingNoticeWorkflowReturn = {
/** 会话内全部开放 Workflow。 */
workflows: Ref<ShippingWorkflow[]>;
/** 当前选中的 Workflow 编号。 */
selectedWorkflowNo: Ref<string | null>;
/** 切换选中批次。 */
selectWorkflow: (workflowNo: string) => void;
/** 当前选中的 Workflow(或 null)。 */
workflow: Ref<ShippingWorkflow | null>;
/** 当前选中 Workflow 下的 Items。 */
items: Ref<ShippingWorkflowItem[]>;
/** 后端 conversation_processing / 由 work_items 合成。 */
processing: Ref<ConversationProcessingProjection | null>;
/** 统一 ShippingProcessing work_items。 */
processingWorkItems: Ref<ShippingProcessingProjection[]>;
loading: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
cancelItem: (
itemNo: string,
payload: { reason: string; expected_lock_version?: number | null },
) => Promise<ShippingWorkflowItem | null>;
reparseItem: (
itemNo: string,
payload: { reason: string; comment?: string | null },
) => Promise<ShippingWorkflowItem | null>;
focusConversationTask: (taskNo: string) => Promise<void>;
markConversationTaskViewed: (taskNo: string) => Promise<void>;
stop: () => void;
};
@@ -108,71 +80,42 @@ function resolvePollMs(): number {
* 失败退避:2s → 4s → 8s(封顶)。
* @param failureCount - 连续失败次数(≥1)
*/
export function resolveWorkflowPollBackoffMs(failureCount: number): number {
export function resolveProcessingPollBackoffMs(failureCount: number): number {
const n = Math.max(1, Math.floor(failureCount));
return Math.min(FOREGROUND_POLL_MS * (2 ** (n - 1)), MAX_BACKOFF_MS);
}
/**
* 在列表中解析应保留的选中 Workflow 编号。
* 核心逻辑:显式 preferred → 仍在列表中的 previous → 首个。
* 判断是否应继续轮询统一 ShippingProcessing。
* 核心逻辑:processing / needs_action 有活跃项则继续。
*/
export function resolveSelectedWorkflowNo(
list: ShippingWorkflow[],
previous: string | null | undefined,
preferred?: string | null,
): string | null {
if (!list.length) return null;
const preferredNo = String(preferred || '').trim();
if (preferredNo && list.some((row) => row.workflow_no === preferredNo)) {
return preferredNo;
}
const previousNo = String(previous || '').trim();
if (previousNo && list.some((row) => row.workflow_no === previousNo)) {
return previousNo;
}
return String(list[0]?.workflow_no || '').trim() || null;
}
/**
* 判断是否应继续轮询。
* 核心逻辑:任一非终态 Workflow 仍有开放处理项则继续;空列表停止(等 refreshTrigger 重启)。
*/
export function shouldContinueWorkflowPolling(
workflows: ShippingWorkflow[],
export function shouldContinueProcessingPolling(
processing?: ConversationProcessingProjection | null,
): boolean {
if (!workflows.length) return false;
return workflows.some((workflow) => {
const status = String(workflow.status || '').trim();
if (TERMINAL_WORKFLOW_STATUSES.has(status)) return false;
const items = Array.isArray(workflow.items) ? workflow.items : [];
const hasOpen = items.some((item) =>
OPEN_ACTIVE_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
return hasOpen || items.length === 0;
});
const processingCount = Number(processing?.summary?.processing || processing?.processing?.length || 0);
const needsActionCount = Number(processing?.summary?.needs_action || processing?.needs_action?.length || 0);
return processingCount > 0 || needsActionCount > 0;
}
/**
* 会话 Workflow 轮询 composable。
* 会话级 ShippingProcessing 轮询 composable。
*
* @param options.conversationId - 会话 ID
* @param options.refreshTrigger - 外部刷新触发器
* @returns workflows / selectedWorkflowNo / selectWorkflow / workflow / items / …
* @returns processing / processingWorkItems / loading / error …
*/
export function useShippingNoticeWorkflow(
options: UseShippingNoticeWorkflowOptions,
): UseShippingNoticeWorkflowReturn {
const workflows = ref<ShippingWorkflow[]>([]);
const selectedWorkflowNo = ref<string | null>(null);
/** 用户显式点选后锁定,直到会话切换或列表不再包含该编号。 */
const explicitSelectionNo = ref<string | null>(null);
const processing = ref<ConversationProcessingProjection | null>(null);
const processingWorkItems = ref<ShippingProcessingProjection[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
let pollTimer: ReturnType<typeof setTimeout> | null = null;
let pollGeneration = 0;
let requestController: AbortController | null = null;
let requestGeneration = 0;
let failureCount = 0;
let pollingStopped = false;
@@ -180,16 +123,6 @@ export function useShippingNoticeWorkflow(
String(readOption(options.conversationId) || '').trim(),
);
const workflow = computed((): ShippingWorkflow | null => {
const no = selectedWorkflowNo.value;
if (!no) return null;
return workflows.value.find((row) => row.workflow_no === no) || null;
});
const items = computed((): ShippingWorkflowItem[] => (
Array.isArray(workflow.value?.items) ? [...workflow.value!.items!] : []
));
/**
* 中止进行中的请求与定时器。
*/
@@ -199,6 +132,7 @@ export function useShippingNoticeWorkflow(
pollTimer = null;
requestController?.abort();
requestController = null;
requestGeneration += 1;
pollGeneration += 1;
}
@@ -215,102 +149,97 @@ export function useShippingNoticeWorkflow(
}
/**
* 用户显式切换批次;写入 preferred 并刷新派生选中项。
*/
function selectWorkflow(workflowNo: string) {
const normalized = String(workflowNo || '').trim();
if (!normalized) return;
if (!workflows.value.some((row) => row.workflow_no === normalized)) return;
explicitSelectionNo.value = normalized;
selectedWorkflowNo.value = normalized;
}
/**
* 根据列表与显式选择同步 selectedWorkflowNo。
*/
function syncSelection(list: ShippingWorkflow[]) {
const next = resolveSelectedWorkflowNo(
list,
selectedWorkflowNo.value,
explicitSelectionNo.value,
);
if (explicitSelectionNo.value && next !== explicitSelectionNo.value) {
explicitSelectionNo.value = null;
}
selectedWorkflowNo.value = next;
}
/**
* 拉取会话开放 Workflow 列表,并保持选中策略。
* 仅拉取统一 shipping-processing 投影。
* 核心逻辑:work_items 非空时始终由 order_task 合成任务列表;embedded 仅补焦点元数据;
* 新请求会中止旧请求,且只有最新一代请求可回写 loading / error / 会话数据。
* @returns Promise<void>;可恢复网络失败写入 error,不向页面抛出。
*/
async function refresh(): Promise<void> {
const conversationId = normalizedConversationId.value;
if (!conversationId) {
workflows.value = [];
selectedWorkflowNo.value = null;
explicitSelectionNo.value = null;
processing.value = null;
processingWorkItems.value = [];
error.value = null;
return;
}
if (loading.value) return;
const generation = ++requestGeneration;
loading.value = true;
const controller = createRequestController();
try {
const projection = await listWorkspaceShippingWorkflows(conversationId, {
signal: controller.signal,
});
if (controller.signal.aborted) return;
const list = Array.isArray(projection.workflows) ? [...projection.workflows] : [];
workflows.value = list;
syncSelection(list);
// [STEP 1] 统一投影为唯一读源。
const unified = await getWorkspaceShippingProcessing(conversationId, controller.signal);
if (
controller.signal.aborted
|| generation !== requestGeneration
|| conversationId !== normalizedConversationId.value
) return;
const workItems = Array.isArray(unified?.work_items) ? unified.work_items : [];
const embedded = unified?.conversation_processing as ConversationProcessingProjection | null | undefined;
processingWorkItems.value = workItems;
processing.value = resolveConversationProcessingFromUnified(workItems, embedded);
error.value = null;
failureCount = 0;
} catch (err) {
if (controller.signal.aborted) return;
} catch (reason) {
if (
controller.signal.aborted
|| generation !== requestGeneration
|| conversationId !== normalizedConversationId.value
) return;
failureCount += 1;
error.value = err instanceof BusinessError
? err.message
error.value = reason instanceof BusinessError
? reason.message
: 'network_recoverable';
} finally {
if (requestController === controller) requestController = null;
loading.value = false;
if (generation === requestGeneration) loading.value = false;
}
}
/**
* 取消单个 Item 后刷新列表。
* 将 focus/viewed/submit 写路径响应应用到本地 processing 与 work_items。
* 核心逻辑:有 work_items 时用统一合成;否则仅回写 processing 兼容块。
*/
async function cancelItem(
itemNo: string,
payload: { reason: string; expected_lock_version?: number | null },
): Promise<ShippingWorkflowItem | null> {
const normalized = String(itemNo || '').trim();
const reason = String(payload.reason || '').trim();
if (!normalized || !reason) return null;
const response = await cancelWorkspaceShippingWorkflowItem(normalized, {
reason,
expected_lock_version: payload.expected_lock_version,
});
await refresh();
return response.item || null;
function applyMutationProcessingResponse(response: {
processing?: ConversationProcessingProjection | null;
work_items?: unknown[];
}): void {
const workItems = Array.isArray(response.work_items) ? response.work_items : [];
if (workItems.length > 0) {
processingWorkItems.value = workItems as typeof processingWorkItems.value;
processing.value = resolveConversationProcessingFromUnified(
workItems as typeof processingWorkItems.value,
response.processing ?? null,
);
return;
}
if (response.processing) processing.value = response.processing;
}
/**
* 重试/重新识别单个 Item 后刷新列表。
* 标记用户可见任务为焦点(写审计并刷新 processing)。
*/
async function reparseItem(
itemNo: string,
payload: { reason: string; comment?: string | null },
): Promise<ShippingWorkflowItem | null> {
const normalized = String(itemNo || '').trim();
const reason = String(payload.reason || '').trim();
if (!normalized || !reason) return null;
const response = await reparseWorkspaceShippingWorkflowItem(normalized, {
reason,
comment: payload.comment,
async function focusConversationTask(taskNo: string): Promise<void> {
const normalized = String(taskNo || '').trim();
const conversationId = normalizedConversationId.value;
if (!normalized || !conversationId) return;
const response = await focusWorkspaceConversationTask(normalized, {
conversation_id: conversationId,
});
await refresh();
return response.item || null;
applyMutationProcessingResponse(response);
}
/**
* 标记用户可见任务已查看(不等于业务已处理)。
*/
async function markConversationTaskViewed(taskNo: string): Promise<void> {
const normalized = String(taskNo || '').trim();
const conversationId = normalizedConversationId.value;
if (!normalized || !conversationId) return;
const response = await markWorkspaceConversationTaskViewed(normalized, {
conversation_id: conversationId,
});
applyMutationProcessingResponse(response);
}
/**
@@ -323,11 +252,15 @@ export function useShippingNoticeWorkflow(
await refresh();
if (generation !== pollGeneration || pollingStopped) return;
if (!normalizedConversationId.value) return;
if (!shouldContinueWorkflowPolling(workflows.value)) {
if (error.value) {
schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount));
return;
}
if (!shouldContinueProcessingPolling(processing.value)) {
return;
}
const nextDelay = failureCount > 0
? resolveWorkflowPollBackoffMs(failureCount)
? resolveProcessingPollBackoffMs(failureCount)
: resolvePollMs();
schedulePoll(generation, nextDelay);
}, delayMs);
@@ -341,16 +274,17 @@ export function useShippingNoticeWorkflow(
pollingStopped = false;
const conversationId = normalizedConversationId.value;
if (!conversationId) {
workflows.value = [];
selectedWorkflowNo.value = null;
explicitSelectionNo.value = null;
error.value = null;
return;
}
const generation = pollGeneration;
void refresh().then(() => {
if (generation !== pollGeneration || pollingStopped) return;
if (!shouldContinueWorkflowPolling(workflows.value)) return;
if (error.value) {
schedulePoll(generation, resolveProcessingPollBackoffMs(failureCount));
return;
}
if (!shouldContinueProcessingPolling(processing.value)) return;
schedulePoll(generation, resolvePollMs());
});
}
@@ -361,8 +295,12 @@ export function useShippingNoticeWorkflow(
schedulePoll(pollGeneration, 0);
}
watch(normalizedConversationId, () => {
explicitSelectionNo.value = null;
watch(normalizedConversationId, (nextConversationId, previousConversationId) => {
if (nextConversationId !== previousConversationId) {
processing.value = null;
processingWorkItems.value = [];
error.value = null;
}
restartPolling();
}, { immediate: true });
@@ -388,16 +326,13 @@ export function useShippingNoticeWorkflow(
}
return {
workflows,
selectedWorkflowNo,
selectWorkflow,
workflow,
items,
processing,
processingWorkItems,
loading,
error,
refresh,
cancelItem,
reparseItem,
focusConversationTask,
markConversationTaskViewed,
stop,
};
}
@@ -11,7 +11,7 @@ import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
import type { ChatMessage } from '../types/chat.types';
const api = vi.hoisted(() => ({
createRun: vi.fn(),
createSubmission: vi.fn(),
getRun: vi.fn(),
listRuns: vi.fn(),
markSeen: vi.fn(),
@@ -22,7 +22,7 @@ const api = vi.hoisted(() => ({
}));
vi.mock('../api/shipping.api', () => ({
createWorkspaceShippingOrderExtractionRun: api.createRun,
createWorkspaceOrderExtractionSubmission: api.createSubmission,
getWorkspaceShippingOrderExtractionRun: api.getRun,
listWorkspaceShippingOrderExtractionRuns: api.listRuns,
markWorkspaceShippingOrderExtractionRunSeen: api.markSeen,
@@ -74,6 +74,8 @@ const createHarness = () => {
onConversationResolved: vi.fn(async () => undefined),
onRetryError: vi.fn(),
onWorkflowRefresh: vi.fn(),
getFocusedUserTaskNo: vi.fn(() => null),
setFocusedUserTaskNo: vi.fn(),
t: (key: string) => key,
};
return { messages, conversationId, options, runs: useShippingOrderExtractionRuns(options) };
@@ -97,30 +99,58 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
});
it('persists stable user and assistant formIds and does not write unchanged polling state again', async () => {
const queued = run({ run_no: 'SNER-START', conversation_id: 'conv-created' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
const queued = run({
run_no: 'SNER-START',
conversation_id: 'conv-created',
user_task_no: 'OT-SNER-START',
});
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-START',
run_no: 'SNER-START',
created_new: true,
operation_id: 'op-1',
});
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-1'], [], 'batch-1');
expect(api.createRun).toHaveBeenCalledWith(expect.objectContaining({ upload_batch_id: 'batch-1' }));
expect(api.createSubmission).toHaveBeenCalledWith(expect.objectContaining({
upload_batch_id: 'batch-1',
intake_nos: ['SNI-1'],
composer_context_id: expect.stringMatching(/^CMP-/),
submission_id: expect.stringMatching(/^SUB-/),
}));
expect(harness.options.setFocusedUserTaskNo).toHaveBeenCalledWith('OT-SNER-START');
expect(harness.conversationId.value).toBe('conv-created');
expect(harness.options.onConversationResolved).toHaveBeenCalledWith('conv-created');
expect(harness.messages.value.map((item) => item.payload?.formId)).toEqual([
'shipping-order-extraction-user:SNER-START',
'shipping-submission-decision:op-1',
'shipping-order-extraction-run:SNER-START',
]);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
await vi.advanceTimersByTimeAsync(1000);
expect(api.getRun).toHaveBeenCalledWith('SNER-START', expect.any(AbortSignal));
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(2);
expect(harness.options.saveLocalMessageToBackend).toHaveBeenCalledTimes(3);
harness.runs.stopPolling();
});
it('persists an attachment-only user message when the run starts without a text note', async () => {
const queued = run({ run_no: 'SNER-EMPTY-NOTE', conversation_id: 'conv-empty-note' });
api.createRun.mockResolvedValue({ run: queued, reused: false });
const queued = run({
run_no: 'SNER-EMPTY-NOTE',
conversation_id: 'conv-empty-note',
user_task_no: 'OT-SNER-EMPTY-NOTE',
});
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-EMPTY-NOTE',
run_no: 'SNER-EMPTY-NOTE',
created_new: true,
operation_id: 'op-empty',
});
api.getRun.mockResolvedValue(queued);
const harness = createHarness();
await harness.runs.startRun('', ['SNI-1'], [{
@@ -181,17 +211,33 @@ describe('useShippingOrderExtractionRuns lifecycle', () => {
});
it('aborts a hanging Run query after ten seconds and keeps polling as a transport failure', async () => {
api.createRun.mockResolvedValue({ run: run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }), reused: false });
api.getRun.mockImplementation((_runNo: string, signal: AbortSignal) => new Promise((_resolve, reject) => {
signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
}));
api.createSubmission.mockResolvedValue({
decision: 'created',
user_task_no: 'OT-SNER-TIMEOUT',
run_no: 'SNER-TIMEOUT',
created_new: true,
operation_id: 'op-timeout',
});
api.getRun.mockResolvedValue(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
// 首次 GET(提交后投影)已返回;后续轮询挂起直至 Abort。
let pollCalls = 0;
api.getRun.mockImplementation((_runNo: string, signal?: AbortSignal) => {
pollCalls += 1;
if (pollCalls === 1) {
return Promise.resolve(run({ run_no: 'SNER-TIMEOUT', conversation_id: 'conv-timeout' }));
}
return new Promise((_resolve, reject) => {
signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')), { once: true });
});
});
const harness = createHarness();
await harness.runs.startRun('解析附件', ['SNI-1'], []);
await vi.advanceTimersByTimeAsync(11000);
expect(api.getRun).toHaveBeenCalledWith('SNER-TIMEOUT', expect.any(AbortSignal));
expect(harness.runs.getActiveRunNo()).toBe('SNER-TIMEOUT');
expect(harness.messages.value[1]?.shipping_order_extraction_state?.status).toBe('queued');
const runMessage = harness.messages.value.find((item) => item.shipping_order_extraction_state);
expect(runMessage?.shipping_order_extraction_state?.status).toBe('queued');
harness.runs.stopPolling();
});
@@ -1,9 +1,10 @@
/**
* features/chat/shipping/useShippingOrderExtractionRuns.ts
* 用途:把货代订单抽取作为独立 Run 启动、轮询并投影到聊天状态消息。
* 依赖:shipping.api Run 接口、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun;本模块持久化本地消息并轮询 Run;终态后仍保留 run_no 供状态卡展示。
* 右侧「本次处理」由 Workflow 投影驱动,本模块仅在终态/重识别后触发其刷新回调。
* 依赖:shipping.api 统一提交/Run 接口、shippingSubmissionFeedback、chat.types、Vue refs。
* 逻辑:发送处理器调用 startRun → createWorkspaceOrderExtractionSubmission(后端裁决 append/create);
* 写入用户消息 + 非阻塞决策系统消息后轮询 Run;终态后仍保留 run_no 供状态卡展示。
* 右侧「本次处理」由 processing / Workflow 投影驱动,本模块在终态/重识别后触发刷新回调。
* 轮询前台 2s / 后台 5–10s;取消走请求语义 API,刷新为只读 GET。
* 持久化去重签名必须包含 handling_items / primary_notice,避免处理说明变化后历史会话仍读到旧卡。
*/
@@ -11,7 +12,7 @@ import { getCurrentInstance, onBeforeUnmount, type ComputedRef, type Ref } from
import {
cancelWorkspaceShippingOrderExtractionDocument,
cancelWorkspaceShippingOrderExtractionRun,
createWorkspaceShippingOrderExtractionRun,
createWorkspaceOrderExtractionSubmission,
getWorkspaceShippingOrderExtractionRun,
listWorkspaceShippingOrderExtractionRuns,
markWorkspaceShippingOrderExtractionRunSeen,
@@ -21,6 +22,11 @@ import {
import type { ChatMessage, ChatMessageAttachment, ShippingOrderExtractionReviewAttachment, ShippingOrderExtractionState } from '../types/chat.types';
import type { ShippingOrderExtractionRun } from '../types/shipping.api.types';
import type { ShippingNoticeCandidate } from '../types/shipping.types';
import {
buildShippingSubmissionFeedback,
createComposerContextId,
createShippingSubmissionId,
} from './shippingSubmissionFeedback';
interface UseShippingOrderExtractionRunsOptions {
messages: Ref<ChatMessage[]>;
@@ -38,6 +44,10 @@ interface UseShippingOrderExtractionRunsOptions {
onRetryError: (message: string) => void;
/** 终态/重识别/恢复后通知右侧 Workflow 面板立即刷新。 */
onWorkflowRefresh?: () => void;
/** 当前页面聚焦的用户可见任务(OT-…);参与追加优先级第 2 档。 */
getFocusedUserTaskNo?: () => string | null;
/** 新建任务后回写焦点,供下次追加与侧栏高亮。 */
setFocusedUserTaskNo?: (taskNo: string | null) => void;
t: (key: string, params?: Record<string, unknown>) => string;
}
@@ -60,6 +70,14 @@ function resolvePollIntervalMs(failureCount = 0): number {
export function mapOrderExtractionRunToMessageState(run: ShippingOrderExtractionRun): ShippingOrderExtractionState {
return {
status: run.status,
userTaskNo: run.user_task_no || null,
submissionOrdinal: run.submission_ordinal ?? null,
composerContextId: run.composer_context_id || null,
runNo: run.run_no,
sourceRunNo: run.reparse?.source_run_no || null,
supersedingRunNo: run.reparse?.superseding_run_no || null,
isCurrent: !run.reparse?.superseding_run_no,
readOnlyReason: run.reparse?.superseding_run_no ? 'superseded_by_newer_run' : null,
summary: {
totalDocuments: Number(run.summary?.total_documents || 0),
pendingDocuments: Number(run.summary?.pending_documents || 0),
@@ -185,6 +203,21 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
let pollFailureCount = 0;
let pollGeneration = 0;
const persistedSignatures = new Map<string, string>();
/** 输入区短生命周期上下文;切会话时轮换,同会话多次发送可命中追加优先级第 1 档。 */
let composerContextId = createComposerContextId();
let composerBoundConversationId = String(options.conversationId.value || '').trim();
/**
* 确保 composer_context_id 绑定当前会话;会话变化时轮换。
*/
function ensureComposerContext(): string {
const conversationId = String(options.conversationId.value || '').trim();
if (conversationId && conversationId !== composerBoundConversationId) {
composerContextId = createComposerContextId();
composerBoundConversationId = conversationId;
}
return composerContextId;
}
/** 停止当前 Run 短轮询;切会话和组件卸载时再清空 activeRunNo。 */
const stopPolling = () => {
@@ -397,11 +430,12 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
};
/**
* 启动订单抽取后台 Run,并把用户操作和状态卡持久化到本地会话。
* 启动订单抽取统一提交:后端裁决 append/create,并把用户操作与状态卡持久化到本地会话。
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。
* @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。
* @returns Run 已成功创建或幂等复用时为 true。
* @param uploadBatchId - 上传批次隔离键;禁止当作 user_task_no。
* @returns 提交成功(含幂等重放)时为 true。
*/
const startRun = async (
query: string,
@@ -410,14 +444,29 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
uploadBatchId?: string,
): Promise<boolean> => {
stopPolling();
const response = await createWorkspaceShippingOrderExtractionRun({
const submissionId = createShippingSubmissionId();
const composerContext = ensureComposerContext();
const focusedUserTaskNo = String(options.getFocusedUserTaskNo?.() || '').trim() || null;
const submission = await createWorkspaceOrderExtractionSubmission({
agent_id: options.currentAgentId.value,
conversation_id: options.conversationId.value || undefined,
conversation_id: options.conversationId.value || '',
intake_nos: intakeNos,
upload_batch_id: uploadBatchId || '',
submission_id: submissionId,
upload_batch_id: uploadBatchId || undefined,
composer_context_id: composerContext,
focused_user_task_no: focusedUserTaskNo,
});
const run = response.run;
if (!options.conversationId.value) options.conversationId.value = run.conversation_id;
// 统一提交只返回决策摘要;再拉 Run 投影供状态卡与轮询。
const run = await getWorkspaceShippingOrderExtractionRun(submission.run_no);
if (!options.conversationId.value) {
options.conversationId.value = run.conversation_id;
composerBoundConversationId = run.conversation_id;
}
const feedback = buildShippingSubmissionFeedback(submission, attachments.length);
const decisionKey = feedback.decision === 'appended'
? 'chat.shippingSubmission.appended'
: 'chat.shippingSubmission.created';
const userMessage: ChatMessage = {
role: 'user',
@@ -429,13 +478,37 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
payload: {
formId: `shipping-order-extraction-user:${run.run_no}`,
order_extraction_run_no: run.run_no,
user_task_no: submission.user_task_no,
submission_decision: feedback.decision,
},
};
options.messages.value.push(userMessage);
await options.saveLocalMessageToBackend(userMessage, query || undefined);
// 非阻塞系统反馈:可回看,不弹窗。
const systemMessage: ChatMessage = {
role: 'assistant',
type: 'text',
content: options.t(decisionKey, { count: feedback.fileCount }),
local_id: options.newLocalMessageId('shipping-submission-decision'),
local_only: true,
payload: {
formId: `shipping-submission-decision:${submission.operation_id || submissionId}`,
submission_decision: feedback.decision,
user_task_no: submission.user_task_no,
run_no: submission.run_no,
},
};
options.messages.value.push(systemMessage);
await options.saveLocalMessageToBackend(systemMessage);
// 新建任务自动聚焦;追加则保持/回写当前 OT。
options.setFocusedUserTaskNo?.(submission.user_task_no || null);
await upsertRunMessage(run);
await acknowledgeTerminalRunWhenVisible(run);
await options.onConversationResolved(run.conversation_id);
options.onWorkflowRefresh?.();
if (ACTIVE_RUN_STATUSES.has(run.status)) {
beginPolling(run.run_no, 1000);
} else {
@@ -0,0 +1,159 @@
/**
* features/chat/shipping/useShippingProcessingWorkItem.ts
* 用途:按 work_item_type + work_item_no 轮询统一 ShippingProcessingProjection。
* 依赖:shipping.api getWorkspaceShippingProcessingWorkItem、normalizeShippingProcessing。
* 逻辑:复核台 / 任务中心双读接入;404 或权威 OT 缺失时保持 null,不打断旧进度 UI。
*/
import {
getCurrentInstance,
onBeforeUnmount,
ref,
watch,
type MaybeRefOrGetter,
type Ref,
toValue,
} from 'vue';
import { BusinessError } from '@/shared/api/client';
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',
'failed',
'cancelled',
]);
export type ShippingProcessingWorkItemTypeArg = 'order_intake' | 'order_task';
/**
* 轮询单个统一处理工作项投影。
*
* @param workItemType - order_intake | order_task
* @param workItemNo - Intake 编号或 OT 编号(MaybeRef)
* @param options.enabled - 是否启用;options.pollMs - 轮询间隔
* @returns projection / loading / error / refresh / stop
*/
export function useShippingProcessingWorkItem(
workItemType: ShippingProcessingWorkItemTypeArg,
workItemNo: MaybeRefOrGetter<string | null | undefined>,
options: {
enabled?: MaybeRefOrGetter<boolean>;
pollMs?: number;
} = {},
): {
projection: Ref<ShippingProcessingProjection | null>;
loading: Ref<boolean>;
error: Ref<string | null>;
refresh: () => Promise<void>;
stop: () => void;
} {
const projection = ref<ShippingProcessingProjection | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
let timer: ReturnType<typeof window.setTimeout> | null = null;
let generation = 0;
let stopped = false;
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
/**
* 清除轮询定时器。
*/
function clearTimer() {
if (timer != null) {
window.clearTimeout(timer);
timer = null;
}
}
/**
* 停止轮询并递增代际,丢弃在途响应写回。
*/
function stop() {
stopped = true;
generation += 1;
clearTimer();
}
/**
* 拉取一次投影;失败保留上一帧。
*/
async function refresh(): Promise<void> {
const no = String(toValue(workItemNo) || '').trim();
const enabled = options.enabled == null ? true : Boolean(toValue(options.enabled));
if (!enabled || !no) {
projection.value = null;
error.value = null;
clearTimer();
return;
}
const gen = generation;
loading.value = true;
try {
const raw = await getWorkspaceShippingProcessingWorkItem(workItemType, no);
if (stopped || gen !== generation) return;
const normalized = normalizeShippingProcessingProjection(raw);
projection.value = normalized;
error.value = null;
clearTimer();
if (normalized && !TERMINAL_STATUSES.has(normalized.status) && !stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
}
} catch (err) {
if (stopped || gen !== generation) return;
// 404 / 业务不存在:清空投影但不抛到页面主流程。
if (err instanceof BusinessError && (err.status === 404 || err.code?.includes('NOT_FOUND'))) {
projection.value = null;
error.value = null;
clearTimer();
return;
}
error.value = err instanceof BusinessError ? err.message : 'network_recoverable';
clearTimer();
if (!stopped) {
timer = window.setTimeout(() => {
void refresh();
}, pollMs);
}
} finally {
if (gen === generation) loading.value = false;
}
}
watch(
() => [String(toValue(workItemNo) || ''), Boolean(toValue(options.enabled ?? true))] as const,
([no, enabled], _prev, onCleanup) => {
stopped = false;
generation += 1;
clearTimer();
onCleanup(() => {
clearTimer();
});
if (!enabled || !no) {
projection.value = null;
error.value = null;
return;
}
void refresh();
},
{ immediate: true },
);
if (getCurrentInstance()) {
onBeforeUnmount(() => {
stop();
});
}
return {
projection,
loading,
error,
refresh,
stop,
};
}
+19 -1
View File
@@ -3,6 +3,9 @@
* 用途:定义聊天域的消息、会话、预览与附件下载等共享类型。
* 依赖:被 chat 页面 composables、消息气泡组件、API 封装共同引用。
* 逻辑:作为 features/chat 域的类型中枢,向上提供页面编排约束,向下约束消息渲染与交互结构。
* 会话多任务聚合阶段 0(2026-08-03):ShippingChatFocusState /
* ShippingOrderExtractionState 增加 userTaskNo、submissionOrdinal、
* composerContextId;与 shipping.api.types 提交 DTO 对齐。
*/
import type { LeaveAgentOption } from './leave.types';
import type { ShippingBatchUiState, ShippingTaskUiState } from './shipping.api.types';
@@ -116,11 +119,14 @@ export interface ShippingOrderExtractionHandlingItemState {
}
/**
* 对话侧栏聚焦对象(阶段 2)。
* 对话侧栏聚焦对象(阶段 2;阶段 0 起含用户可见任务)。
* 用途:复核返回 / 侧栏点击后恢复「本次处理中」焦点;不替代后端状态。
* 约束:优先恢复 userTaskNo;runNo/taskNo 仅作映射辅助,不得单独充当批次主标题。
*/
export interface ShippingChatFocusState {
conversationId?: string | null;
/** 用户可见任务号(OT-…);会话聚合主焦点键 */
userTaskNo?: string | null;
runNo?: string | null;
candidateNo?: string | null;
taskNo?: string | null;
@@ -131,6 +137,18 @@ export interface ShippingChatFocusState {
export interface ShippingOrderExtractionState {
status: ShippingOrderExtractionStateStatus;
/** 用户可见任务号;重试/扩批/恢复不更换本号 */
userTaskNo?: string | null;
/** 会话内第 N 次用户可见提交(从 1 起) */
submissionOrdinal?: number | null;
/** 当前输入区短生命周期上下文;发送决策用,非业务主键 */
composerContextId?: string | null;
/** Run 版本谱系;由后端投影,供历史消息只读隔离。 */
runNo?: string | null;
sourceRunNo?: string | null;
supersedingRunNo?: string | null;
isCurrent?: boolean;
readOnlyReason?: string | null;
summary: ShippingOrderExtractionStateSummary;
currentActivity?: ShippingOrderExtractionCurrentActivityState | null;
selectionPlan?: ShippingOrderExtractionSelectionPlanState | null;
@@ -10,8 +10,187 @@
* 双工作台架构阶段 0(2026-08-02):WorkbenchSurface /
* CandidateQualificationStatus / WorkflowNodeStatus 冻结;权威见
* docs/features/shipping-notice/review-workbench-layout-plan.md §0。
* 会话多任务聚合阶段 0(2026-08-03):ConversationProcessingTask* /
* OrderExtractionSubmission* / can_append 冻结;权威见 technical.md §1.6.1。
* 多 EML / 直接 PDF / PDF 优先阶段 0(2026-08-04):ShippingProcessing* /
* OrderIntakeSourceType 冻结;权威见 technical.md §1.6.2。过渡期与
* ConversationProcessing* 并存,阶段 5 四页面切到统一投影。
*/
/** Intake 来源类型:一份 EML 或一份直接上传 PDF(禁止泛化 direct_file)。 */
export type OrderIntakeSourceType = 'eml' | 'direct_pdf';
/** 四页面统一工作项类型;未建 OT 为 Intake,已建 OT 后页面身份为 OT。 */
export type ShippingProcessingWorkItemType = 'order_intake' | 'order_task';
/**
* 统一进度 status(后端投影;前端只做 i18n)。
* 权威:progress_audit_contract.SHIPPING_PROCESSING_STATUSES
*/
export type ShippingProcessingStatus =
| 'processing'
| 'waiting_review'
| 'blocked'
| 'automating'
| 'completed'
| 'failed'
| 'cancelled';
/**
* 统一进度 stage(固定 15 阶顺序)。
* 库存源解析必须在 waiting_review / order_creating 之前。
* 直接 PDF 不得进入 email_parsing / email_adjudicating(标记 skipped,禁止删阶)。
* 权威:progress_audit_contract.SHIPPING_PROCESSING_STAGES
*/
export type ShippingProcessingStage =
| 'upload_received'
| 'email_parsing'
| 'document_parsing'
| 'email_adjudicating'
| 'candidate_creating'
| 'customer_resolving'
| 'duplicate_checking'
| 'inventory_source_resolving'
| 'waiting_review'
| 'order_creating'
| 'inventory_fetching'
| 'inventory_matching'
| 'excel_generating'
| 'freight_uploading'
| 'completed';
/** 进度轨道节点执行态(与投影 status 不同)。 */
export type ShippingProcessingStageNodeStatus =
| 'skipped'
| 'pending'
| 'running'
| 'passed'
| 'blocked'
| 'failed';
/**
* 统一动作意图(四页面只能消费 ActionPresentation)。
* 权威:progress_audit_contract.SHIPPING_PROCESSING_ACTION_INTENTS
*/
export type ShippingProcessingActionIntent =
| 'none'
| 'open_order_review'
| 'edit_formal_task'
| 'open_inventory_source_review'
| 'open_inventory_match_review'
| 'open_shortage_review'
| 'upload_inventory_file'
| 'retry'
| 'refresh'
| 'regenerate_excel'
| 'download_excel'
| 'open_manual_upload'
| 'view_result'
| 'view_record';
/** 与后端 SHIPPING_PROCESSING_STAGES 对齐的有序元组(前端密度窗口用)。 */
export const SHIPPING_PROCESSING_STAGES: readonly ShippingProcessingStage[] = [
'upload_received',
'email_parsing',
'document_parsing',
'email_adjudicating',
'candidate_creating',
'customer_resolving',
'duplicate_checking',
'inventory_source_resolving',
'waiting_review',
'order_creating',
'inventory_fetching',
'inventory_matching',
'excel_generating',
'freight_uploading',
'completed',
] as const;
/** EML 专属阶段:直接 PDF 必须 skipped。 */
export const EML_ONLY_PROCESSING_STAGES: ReadonlySet<ShippingProcessingStage> = new Set([
'email_parsing',
'email_adjudicating',
]);
/** 字段证据来源(PDF 优先裁决审计)。 */
export type ShippingProcessingValueSource =
| 'primary_pdf'
| 'email_body'
| 'excel'
| 'word'
| 'image'
| 'model_suggestion';
/** PDF 优先字段策略码(与 PDF_PRIORITY_FIELD_POLICIES 对齐)。 */
export type PdfPriorityFieldPolicy =
| 'prefer'
| 'prefer_with_critical_conflict_gate'
| 'supplement_allowed'
| 'review_required';
/**
* 统一处理投影 DTO(阶段 4 接线;阶段 0 冻结形状)。
* 对话、对话右侧、复核工作台、后台工作台共同消费;禁止页面私自拼接状态。
*/
export interface ShippingProcessingProjection {
workItemType: ShippingProcessingWorkItemType;
workItemNo: string;
sourceType: OrderIntakeSourceType;
rootOrderTaskNo: string | null;
shippingNoticeNo: string | null;
conversationId: string | null;
submissionNo: string;
intakeNo: string;
status: ShippingProcessingStatus;
stage: ShippingProcessingStage;
progressVersion: number;
lastActivityAt: string;
currentGate: ProcessGateSummary | null;
availableActions: string[];
sourceSummary: {
emailSubject: string | null;
filename: string | null;
documentCount: number;
parsedDocumentCount: number;
candidateCount: number;
customerName: string | null;
poNumber: string | null;
/** Intake 解析失败原因码;成功时为 null。 */
failureReasonCode?: string | null;
/** 解析 Job Attempt 次数。 */
parseAttemptCount?: number;
/** FileAsset.status,用于判断原文件是否仍可用。 */
assetStatus?: string | null;
};
childOrderTasks: ShippingOrderTaskSummary[];
}
/**
* OT 摘要(Intake 子项或工作台列表行)。
* 阶段 0 仅冻结字段名;阶段 3+ 由后端投影填充。
*/
export interface ShippingOrderTaskSummary {
orderTaskNo: string;
status: ShippingProcessingStatus;
stage: ShippingProcessingStage;
customerName?: string | null;
poNumber?: string | null;
lastActivityAt?: string | null;
}
/**
* Process Gate 摘要(统一投影内嵌;完整 Gate DTO 见 ShippingProcessGate*)。
*/
export interface ProcessGateSummary {
gateCode: string;
status: string;
nextActionCode?: string | null;
blockingReasonCode?: string | null;
/** Intake / Gate Attempt 次数(可选扩展)。 */
attemptNo?: number | null;
}
/**
* 工作台表面归属(双工作台架构 2026-08-02 冻结)。
* 用途:标注 UI/动作应落在对话、复核或 Task 备用深链,禁止三表面平行主入口。
@@ -54,6 +233,7 @@ export type WorkflowNodeStatus =
*/
export type ConversationProcessingObjectKind =
| 'run'
| 'document'
| 'candidate'
| 'task'
| 'process_gate';
@@ -63,7 +243,7 @@ export type ConversationProcessingObjectKind =
*/
export interface ConversationProcessingObject {
kind: ConversationProcessingObjectKind;
/** 稳定展示键,如 RUN-xxx / CAND-xxx / SN-xxx / gate:code */
/** 稳定展示键,如 RUN-xxx / DOC-xxx / CAND-xxx / SN-xxx / gate:code */
object_key: string;
label: string;
status_label?: string | null;
@@ -74,10 +254,156 @@ export interface ConversationProcessingObject {
task_no?: string | null;
case_no?: string | null;
document_id?: number | null;
root_document_id?: number | null;
filename?: string | null;
content_hash?: string | null;
current_run_no?: string | null;
current_version_no?: number | null;
workflow_item_no?: string | null;
/** 所属用户可见任务号(OT-…);Run 编号不得充当本字段 */
user_task_no?: string | null;
primary_action?: string | null;
focused?: boolean;
}
/** 任务卡展示类型:单 PDF 用文件名;多 PDF 由前端 i18n 渲染任务级标题。 */
export type ConversationProcessingDisplayKind =
| 'single_document_task'
| 'multi_document_task';
/**
* 会话「本次处理中」顶层任务分组(与 progress_audit_contract 对齐)。
* 用途:右侧总卡片按 needs_action / processing / completed / history 分区;禁止前端私造分组名。
*/
export type ConversationProcessingTaskGroup = 'needs_action' | 'processing' | 'completed' | 'history';
/**
* 统一提交决策结果(后端事务裁决;前端只消费,不得本地推导)。
*/
export type ConversationProcessingSubmissionDecision = 'appended' | 'created';
/**
* 输入追加阻断原因码(与 CONVERSATION_PROCESSING_APPEND_BLOCK_REASONS 对齐)。
*/
export type ConversationProcessingAppendBlockReason =
| 'input_already_frozen'
| 'task_closed'
| 'task_cancelled'
| 'no_appendable_context'
| 'composer_context_mismatch'
| 'concurrent_freeze'
| 'submission_idempotent_replay';
/**
* 用户可见任务输入生命周期(不对用户展示原文案;前端只消费 can_append)。
*/
export type ConversationUserTaskInputLifecycle = 'open' | 'freezing' | 'frozen' | 'closed';
/**
* 会话级用户可见任务摘要(阶段 1+ processing API 投影)。
* 用途:右侧任务卡主对象;一次用户发送原则上对应一个;内部可含多 Unit/Attempt。
*/
export interface ConversationProcessingUserTask {
user_task_no: string;
/**
* 为 false 时表示 user_task_no 仅是降级本地兼容号(如 OT-${runNo}),
* 禁止传给 focus / viewed 等后端写接口。
*/
user_task_authoritative?: boolean;
/** 会话内提交序号(第 N 次用户可见提交);从 1 起 */
submission_ordinal?: number | null;
/** 单 PDF 时为文件名;多 PDF 时为 null,禁止用首个文件名伪装单文件任务 */
title?: string | null;
/** single_document_task | multi_document_task;缺省时前端用 file_count 推断 */
display_kind?: ConversationProcessingDisplayKind | string | null;
/** 去重后的 PDF 文件名列表,供多文件副标题预览 */
document_names?: string[] | null;
group: ConversationProcessingTaskGroup;
status_label?: string | null;
/** 去重后的业务 PDF 数(非快照原始行数) */
file_count?: number | null;
/** 当前执行 Run;详情/诊断用,不作主标题 */
run_no?: string | null;
workflow_no?: string | null;
can_append: boolean;
append_block_reason?: ConversationProcessingAppendBlockReason | string | null;
input_lifecycle?: ConversationUserTaskInputLifecycle | string | null;
input_frozen_at?: string | null;
focused?: boolean;
viewed?: boolean;
acknowledged?: boolean;
last_activity_at?: string | null;
created_at?: string | null;
/** 短时反馈:刚刚新增附件数 / 刚刚创建 */
recent_append_count?: number | null;
recently_created?: boolean;
primary_action?: string | null;
available_actions?: string[];
objects?: ConversationProcessingObject[];
}
/**
* 会话级 processing 汇总计数。
*/
export interface ConversationProcessingSummary {
total_tasks: number;
/** 当前活跃任务覆盖的文件数(按 PDF 归并后) */
total_files?: number;
processing: number;
needs_action: number;
/** 识别完成且尚未查看的成功通知数 */
completed?: number;
history: number;
}
/**
* GET conversations/{id}/processing 与提交响应内嵌投影(阶段 1)。
*/
export interface ConversationProcessingProjection {
summary: ConversationProcessingSummary;
focused_task_no?: string | null;
recent_task_no?: string | null;
needs_action: ConversationProcessingUserTask[];
processing: ConversationProcessingUserTask[];
/** 成功完成待查看;与 needs_action 异常态分离 */
completed?: ConversationProcessingUserTask[];
history: ConversationProcessingUserTask[];
}
/**
* POST order-extraction-submissions 请求体(阶段 1;阶段 0 仅冻结形状)。
* 约束:submission_id 为客户端幂等键;composer_context_id 非业务主键;
* upload_batch_id 不得充当 user_task_no。
*/
export interface OrderExtractionSubmissionRequest {
conversation_id: string;
agent_id: number;
intake_nos: string[];
submission_id: string;
composer_context_id?: string | null;
/** 可选:页面显式聚焦的用户可见任务,参与追加优先级第 2 档 */
focused_user_task_no?: string | null;
upload_batch_id?: string | null;
}
/**
* 统一提交响应(后端裁决追加或新建)。
*/
export interface OrderExtractionSubmissionResponse {
decision: ConversationProcessingSubmissionDecision;
user_task_no: string;
run_no: string;
created_new: boolean;
reason_code?: ConversationProcessingAppendBlockReason | string | null;
message?: string | null;
operation_id?: string | null;
reused?: boolean;
can_append?: boolean;
append_block_reason?: ConversationProcessingAppendBlockReason | string | null;
input_frozen_at?: string | null;
processing?: ConversationProcessingProjection | null;
}
export type InventorySourceStatus =
| 'unresolved'
| 'ambiguous'
@@ -196,15 +522,24 @@ export interface ShippingTaskSummary {
ui_state?: ShippingTaskUiState;
/** 待办分类:review | exception | manual_upload | in_progress | done */
todo_category?: string | null;
/** task | review_case;复核项无 task_no,用 review_run_no 深链 */
item_kind?: 'task' | 'review_case' | string | null;
/** task | review_case | order_intake;复核项无 task_no,用 review_run_no 深链 */
item_kind?: 'task' | 'review_case' | 'order_intake' | string | null;
todo_ref?: string | null;
review_run_no?: string | null;
review_case_no?: string | null;
review_case_status?: string | null;
/** 未建 OT 的 Intake 编号(材料解析待办)。 */
intake_no?: string | null;
intake_parse_status?: string | null;
owner_agent_id?: number | null;
/** 当前用户是否可写;管理员查看他人任务时为 false */
can_handle?: boolean;
/** 统一 ShippingProcessing status(列表轮询优先读此字段)。 */
shipping_processing_status?: string | null;
/** 统一进度版本(与 shipping_processing_status 配套)。 */
progress_version?: number | null;
/** 关联的真实 OT 编号(Candidate 形成后);工作台拉取统一投影用。 */
order_task_no?: string | null;
created_by?: number | null;
/** 业务版本号;修订建单时递增 */
document_version?: number;
@@ -406,6 +741,8 @@ export interface ShippingProcessGateUserSummary {
/** 统一可解释性投影(与 build_explainability_reason 对齐) */
explainability?: ShippingExplainabilityReason | null;
next_action_code?: ShippingProcessGateActionCode | string | null;
/** 当前阻断仅剩技术自动恢复时为 true(业务用户无写操作) */
technical_auto_only?: boolean;
responsible_party?: ShippingProcessGateResponsibleParty | string | null;
diagnostic_hint?: string | null;
case_no?: string | null;
@@ -1054,6 +1391,14 @@ export interface ShippingOrderExtractionDocumentResult {
export interface ShippingOrderExtractionRun {
run_no: string;
/** 用户可见任务号(OT-…);重试/扩批不更换 */
user_task_no?: string | null;
submission_ordinal?: number | null;
composer_context_id?: string | null;
can_append?: boolean;
append_block_reason?: ConversationProcessingAppendBlockReason | string | null;
input_lifecycle?: ConversationUserTaskInputLifecycle | string | null;
input_frozen_at?: string | null;
agent_id: number;
conversation_id: string;
status: ShippingOrderExtractionRunStatus;
@@ -1247,7 +1592,9 @@ export type ReviewWorkbenchMode =
| 'evidence'
| 'inventory'
| 'reparse'
| 'confirm_progress';
| 'confirm_progress'
/** 确认建单后:原地编辑正式任务(字段默认只读,Schema 放行可写)。 */
| 'formal_task';
/**
* 复核工作台辅助面板开关状态(前端 UI 契约)。
@@ -1317,6 +1664,13 @@ export interface ShippingOrderReviewSchemaField {
value_type: string;
required: boolean;
options: unknown[];
/** Schema 正式任务编辑策略;仅 confirmed Case 投影携带。 */
task_edit_policy?: {
editable?: boolean;
editable_until?: string | null;
change_effect?: string;
on_revalidation_failure?: string;
};
}
/** 草稿字段值来源元数据;与后端 order_review_projection.field_meta 对齐。 */
@@ -1476,10 +1830,19 @@ export interface ShippingOrderReviewBuildEligibilityIssue {
line_key?: string | null;
line_index?: number;
field_code?: string;
reason_code?: string;
finding_code?: string;
candidate_inventory_source_codes?: string[];
raw_rule_source_codes?: string[];
message?: string | null;
unavailable_source_codes?: string[];
unavailable_reasons?: Record<string, ShippingInventorySourceUnavailableReasonCode>;
explainability?: ShippingExplainabilityReason | null;
low_confidence_fields?: Array<{
field_code: string;
confidence?: number | null;
minimum_confidence?: number | null;
}>;
[key: string]: unknown;
}
@@ -1495,6 +1858,15 @@ export interface ShippingOrderReviewBuildEligibility {
enabled_inventory_source_codes?: string[];
/** 库存源编码 → 业务显示名;复核台展示用,提交仍用编码 */
inventory_source_labels?: Record<string, string>;
assessment?: { missing_required_fields?: string[]; invalid_lines?: unknown[]; [key: string]: unknown };
auto_create_diagnostics?: {
failed_gates?: string[];
reason_codes?: string[];
confidence_policy?: { minimum_confidence?: number; source?: string };
parser_source?: string;
};
/** 资格检查的用户态失败原因,禁止直接展示内部 gate 枚举。 */
auto_create_failure_reasons?: Array<{ code: string; message: string }>;
}
export interface ShippingOrderReviewInventoryCandidatesWrite {
@@ -1529,13 +1901,27 @@ export interface ShippingOrderReviewCustomerResolution {
short_code?: string | null;
candidates?: Array<Record<string, unknown>>;
match?: ShippingOrderCustomerMatch | null;
input_values?: Array<{
definition_code?: string | null;
definition_label?: string | null;
raw_value?: string | null;
normalized_value?: string | null;
}>;
evidence?: Array<Record<string, unknown>>;
}
/** 建单前字段冲突选项(规范化键 + 可展示值)。 */
/** 建单前字段冲突选项(规范化键 + 可展示值 + PDF 优先证据角色)。 */
export interface ShippingOrderReviewFieldConflictOption {
value_key: string;
display_value?: unknown;
sources?: string[];
/** Observation.source_type(主来源)。 */
source_type?: string | null;
source_types?: string[];
/** primary_pdf | auxiliary | context */
evidence_role?: 'primary_pdf' | 'auxiliary' | 'context' | string | null;
/** PDF_PRIORITY_EVIDENCE_RANKS 档位名。 */
evidence_rank?: string | null;
}
/** 建单前 Candidate 字段冲突投影(复核工作台集中裁决区)。 */
@@ -1553,6 +1939,10 @@ export interface ShippingOrderReviewFieldConflict {
export interface ShippingOrderReviewCase {
case_no: string;
run_no: string;
/** 当前 Case 绑定的 Candidate 主键;多 Candidate 时禁止回退 Run 根 OT。 */
candidate_id?: number | null;
/** 当前 Candidate 对应的真实 OT 编号;供复核合成进度上下文与统一投影轮询。 */
order_task_no?: string | null;
document: { id: number; file_name?: string | null };
/** 建单前客户确认状态;工作台始终展示,不依赖 Process Gate */
customer_resolution?: ShippingOrderReviewCustomerResolution | null;
@@ -1562,6 +1952,10 @@ export interface ShippingOrderReviewCase {
duplicate?: ShippingOrderReviewDuplicate | null;
/** 建单前文档模板匹配只读摘要 */
profile_match?: ShippingOrderReviewProfileMatch | null;
/** 建单前 Reservation 校验摘要 */
reservation?: ShippingOrderReviewReservation | null;
/** 行级履约决定与库存缺口摘要 */
line_fulfillment?: ShippingOrderReviewLineFulfillment | null;
status: string;
disposition?: string | null;
confirmed_task_id?: number | null;
@@ -1600,6 +1994,10 @@ export interface ShippingOrderReviewCase {
build_eligibility?: ShippingOrderReviewBuildEligibility;
} | null;
available_actions: string[];
/** 正式任务 Schema 放行可写字段 field_id;confirmed + edit_formal_task 时由后端投影。 */
formal_editable_field_ids?: string[];
/** 关联 Notice 的 order_data_version;formal patch 乐观锁。 */
order_data_version?: number | null;
llm_suggestions?: ShippingOrderReviewLlmSuggestion[];
process_gate?: ShippingProcessGateUserSummary | null;
}
@@ -1615,7 +2013,12 @@ export type ShippingOrderReviewConfirmOutcome =
| string;
export interface ShippingOrderReviewConfirmResponse {
/** 正式 Shipping Notice 业务编号(SN);不得当作 OT 写入 user_task_no。 */
task_no?: string | null;
/** 确认后 Candidate 对应的真实 OT 编号;统一 ShippingProcessing 轮询须读此字段。 */
order_task_no?: string | null;
/** 与 task_no 同义的 Notice 编号别名(部分响应路径可能只返回其一)。 */
shipping_notice_no?: string | null;
idempotent_replay: boolean;
case: ShippingOrderReviewCase;
/** Workflow 业务编号(workflow_no) */
@@ -1705,6 +2108,8 @@ export interface ShippingOrderReviewLlmSuggestion {
scope: string;
evidence_level: string;
status: string;
error_code?: string | null;
error_message?: string | null;
suggested_value?: unknown;
validation_issues?: Array<{ code?: string; severity?: string }>;
decision?: string | null;
@@ -1857,20 +2262,158 @@ export interface ShippingOrderReviewProfileMatch {
};
}
/** 建单前 Reservation 行级投影。 */
export interface ShippingOrderReviewReservationLine {
line_index?: number;
line_key?: string | null;
effective_reservation_id?: string | null;
can_build?: boolean;
block_reason?: string | null;
needs_attention?: boolean;
}
/** 建单前 Reservation 阻断 issue。 */
export interface ShippingOrderReviewReservationIssue {
code?: string | null;
severity?: string;
message?: string | null;
line_index?: number | null;
line_key?: string | null;
field_code?: string | null;
}
/** 建单前 Reservation 校验摘要(Case.reservation)。 */
export interface ShippingOrderReviewReservation {
needs_attention: boolean;
status: string;
reservation_field_id?: string | null;
lines: ShippingOrderReviewReservationLine[];
issues: ShippingOrderReviewReservationIssue[];
}
/** 行级履约决定历史/活动版本。 */
export interface ShippingOrderReviewLineFulfillmentDecision {
id?: number;
line_key?: string;
line_index?: number | null;
decision_version?: number;
decision_code?: string;
line_status?: string;
is_active?: boolean;
reason?: string | null;
required_qty?: string | null;
available_qty?: string | null;
reservation_id?: string | null;
part_number?: string | null;
task_id?: number | null;
wave_no?: number | null;
created_at?: string | null;
}
/** 行级履约决定码(与后端 ALLOWED_DECISIONS 对齐)。 */
export type ShippingOrderReviewLineFulfillmentDecisionCode =
| 'wait_inventory'
| 'fulfill_complete_line_now'
| 'close_unfulfillable'
| 'reopen'
| 'use_new_inventory_file'
| 'change_inventory_source';
/** 行级履约与库存缺口投影行。 */
export interface ShippingOrderReviewLineFulfillmentLine {
line_key: string;
line_index?: number | null;
reservation_id?: string | null;
part_number?: string | null;
required_qty?: string | null;
available_qty?: string | null;
shortage_qty?: string | null;
can_fulfill_complete_line?: boolean;
line_status?: string;
decision?: ShippingOrderReviewLineFulfillmentDecision | null;
block_reason?: string | null;
}
/** Case 行级履约决定聚合(Case.line_fulfillment)。 */
export interface ShippingOrderReviewLineFulfillment {
lines: ShippingOrderReviewLineFulfillmentLine[];
open_count?: number;
ready_count?: number;
has_open_lines?: boolean;
has_shortage?: boolean;
}
/** 复核 Case 业务审计时间线条目(含白名单前后快照;敏感事件脱敏)。 */
export interface ShippingOrderReviewAuditTimelineItem {
id: number;
event_type?: string;
action?: string | null;
result?: string | null;
actor_type?: string;
actor_display?: string | null;
task_no?: string | null;
error_code?: string | null;
reason?: string | null;
reason_code?: string | null;
metadata?: Record<string, unknown>;
created_at?: string | null;
source?: string | null;
has_snapshots?: boolean;
sensitive_redacted?: boolean;
before_snapshot?: Record<string, unknown> | null;
after_snapshot?: Record<string, unknown> | null;
diff?: Array<{ path?: string; before?: unknown; after?: unknown } | string>;
}
/** GET audit-timeline 分页响应。 */
export interface ShippingOrderReviewAuditTimelinePage {
items: ShippingOrderReviewAuditTimelineItem[];
total: number;
page: number;
page_size: number;
case_no: string;
}
/** 任务工作台统一审计时间线条目(与 Case 审计条目同形)。 */
export type ShippingTaskAuditTimelineItem = ShippingOrderReviewAuditTimelineItem;
/** GET /shipping-tasks/:taskNo/audit-timeline 分页响应。 */
export interface ShippingTaskAuditTimelinePage {
items: ShippingTaskAuditTimelineItem[];
total: number;
page: number;
page_size: number;
task_no: string;
}
/** 统一恢复协调器结果(Gate / 资格 / auto_gate 三层分离)。 */
export interface ShippingOrderReviewResumeOutcome {
gate_recalculated?: boolean;
qualification_status?: string | null;
qualification_ready?: boolean;
can_build?: boolean;
auto_gate_allowed?: boolean;
task_created?: boolean;
task_no?: string | null;
auto_progress_started?: boolean;
idempotent_replay?: boolean;
outcome?:
| 'noop'
| 'blocked'
| 'waiting_manual_confirm'
| 'auto_created'
| 'idempotent_replay'
| 'auto_create_failed'
| 'already_confirmed'
| 'no_draft'
| string;
message?: string | null;
failed_gates?: string[];
}
export interface ShippingCreateBatchFromIntakesResponse extends ShippingNoticeUploadResponse {}
/** Workflow 批次状态;与后端 ShippingNoticeWorkflow.status 对齐。 */
export type ShippingWorkflowStatus =
| 'open'
| 'completed'
| 'cancelled'
| 'failed'
| string;
/**
* WorkflowItem 生命周期;与 workflow_progress_projection / ledger 对齐。
* 含 layout_parsing 等版面阶段(尚无 Review Case)。
*/
/** WorkflowItem 生命周期;侧栏文件行 / 复核合成形态仍用此枚举(非台账 API)。 */
export type ShippingWorkflowItemLifecycleStatus =
| 'queued'
| 'layout_parsing'
@@ -1886,18 +2429,7 @@ export type ShippingWorkflowItemLifecycleStatus =
| 'manual_upload_pending'
| string;
/** Workflow 内 Item 用户态计数;与后端 _item_counts 对齐。 */
export interface ShippingWorkflowItemCounts {
total: number;
processing: number;
pending_review: number;
/** 待人工上传登记;非完成。 */
waiting_manual_upload: number;
failed: number;
completed: number;
}
/** 单条用户可见 WorkflowEvent;与 serialize_workflow_event 对齐。 */
/** 单条用户可见 WorkflowEvent;任务详情 / 复核进度仍可附带。 */
export interface ShippingWorkflowEvent {
seq_no: number;
event_code: string;
@@ -1913,7 +2445,10 @@ export interface ShippingWorkflowEvent {
occurred_at?: string | null;
}
/** 单条 WorkflowItem 用户态投影;与 serialize_workflow_item 对齐。 */
/**
* 侧栏文件行 / 复核合成投影形态(原 WorkflowItem;台账 API 已 DROP)。
* 生产由 mapUserTaskObjectsToFileRows 从 OT objects 合成。
*/
export interface ShippingWorkflowItem {
item_no: string;
workflow_no: string;
@@ -1922,6 +2457,20 @@ export interface ShippingWorkflowItem {
current_document_id: number;
/** 当前文档文件名;列表主标题优先展示,缺失时回退展示。 */
current_document_filename?: string | null;
/**
* 当前/根 Document 内容哈希;会话降级投影优先用其跨上传批次归并同一 PDF。
* 与 root_document_id 解耦:普通重传会产生新 Document。
*/
content_hash?: string | null;
/**
* 当前 Run 绑定的用户可见任务号;后端继承后可跨重传保持同一业务身份。
*/
user_task_no?: string | null;
/**
* 为 false 时表示 user_task_no 仅为降级本地兼容号(如 OT-${runNo}),
* 不得用于统一投影 / 已查看等权威 OT API。
*/
user_task_authoritative?: boolean;
current_version_no: number;
current_run_no?: string | null;
current_case_no?: string | null;
@@ -1950,9 +2499,24 @@ export interface ShippingWorkflowItem {
available_actions?: string[];
/** case_version=新建识别版本;failed_run_retry=原失败 Run 重试。 */
reparse_kind?: 'case_version' | 'failed_run_retry' | string | null;
/** reparse_failed 时当前字段/模板实际来自的已恢复成功版本。 */
displayed_version?: {
version_no: number;
run_no?: string | null;
case_no?: string | null;
status: 'restored' | string;
} | null;
/** reparse_failed 时仅用于提示的最新失败尝试,不得作为当前字段版本展示。 */
latest_attempt?: {
version_no: number;
run_no?: string | null;
status?: string | null;
failure_stage?: string | null;
error_code?: string | null;
} | null;
/** 详情接口 include_events=true 时附带。 */
events?: ShippingWorkflowEvent[];
/** 当前 WorkflowItem 版本关联 Execution 的用户 Gate 摘要。 */
/** 当前文件行关联 Execution 的用户 Gate 摘要。 */
process_gate?: ShippingProcessGateUserSummary | null;
gate_user_hint?: string | null;
/** 绑定 Task 时由后端投影的固定节点梯;前端禁止自行算百分比。 */
@@ -1961,30 +2525,14 @@ export interface ShippingWorkflowItem {
node_status?: WorkflowNodeStatus | string | null;
}
/** Workflow 批次投影;与 serialize_workflow 对齐。 */
export interface ShippingWorkflow {
workflow_no: string;
conversation_id: string;
status: ShippingWorkflowStatus;
current_stage: string;
closed_reason?: string | null;
lock_version: number;
counts: ShippingWorkflowItemCounts;
last_activity_at?: string | null;
closed_at?: string | null;
created_at?: string | null;
updated_at?: string | null;
items?: ShippingWorkflowItem[];
}
/** 会话开放 Workflow 列表投影;与 project_conversation_workflows 对齐。 */
export interface ShippingWorkflowConversationProjection {
conversation_id: string;
workflows: ShippingWorkflow[];
}
/**
* 复核页合成进度上下文(权威命名);形状与已下线 WorkflowItem 台账解耦。
* 实际字段仍复用 ShippingWorkflowItem,避免一次大范围重命名破坏侧栏文件行。
*/
export type ShippingReviewProgressContext = ShippingWorkflowItem;
/**
* 复核页版本历史行;后端暂无独立 versions 接口时由 WorkflowItem 派生。
* 复核页版本历史行;后端暂无独立 versions 接口时由合成 Item 派生。
* 保留 case_no 以便 ReviewVersionHistoryPanel 跳转。
*/
export interface ShippingWorkflowItemVersion {
@@ -2001,6 +2549,9 @@ export interface ShippingWorkflowItemVersion {
note?: string | null;
}
/** 复核版本历史行的权威别名(与 ShippingReviewProgressContext 配套)。 */
export type ShippingReviewProgressVersion = ShippingWorkflowItemVersion;
export interface ShippingDecisionResponse {
status: string;
message?: string;
@@ -60,6 +60,7 @@ const reviewRun = ref({
},
],
});
const workItem = ref<Record<string, any> | null>(null);
const activeCase = ref({
case_no: 'CASE-1',
@@ -78,6 +79,15 @@ const activeCase = ref({
required: true,
options: [],
},
{
field_id: 'fld-inventory-source-hint',
field_code: 'inventory_source_hint',
display_name: '库存源线索',
scope: 'line',
value_type: 'string',
required: false,
options: [],
},
],
},
draft: {
@@ -86,7 +96,11 @@ const activeCase = ref({
values: { 'fld-po': { value: 'PO-1', source: 'machine' } },
machine_fields: [{ field_id: 'fld-po', observations: [{ value: 'PO-1' }] }],
},
lines: [],
lines: [{
line_key: 'LINE-1',
values: {},
machine_fields: [],
}],
issues: [],
},
process_gate: null,
@@ -107,7 +121,7 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
useShippingOrderReview: () => ({
reviewRun,
activeCase,
workItem: ref(null),
workItem,
versions: ref([]),
statusMessage: ref(null),
draftConflict: ref(null),
@@ -168,10 +182,20 @@ vi.mock('@/features/chat/shipping-review/useShippingOrderReview', () => ({
editable: computed(() => true),
showWorkflowProgress: computed(() => false),
workflowProgressPolling: computed(() => false),
shippingProcessingProjection: ref(null),
shippingProcessingLoading: ref(false),
shippingProcessingError: ref(null),
refreshShippingProcessing: vi.fn(),
reparseProgressActive: computed(() => false),
reparseProgressPolling: computed(() => false),
reparseProgressRefreshFailed: computed(() => false),
reparseProgressStage: computed(() => 'submitted'),
reparseLastStableStage: computed(() => 'submitted'),
reparseRunStatus: computed(() => 'queued'),
reparseLastActivityAt: computed(() => null),
reparseLastRefreshedAt: computed(() => null),
reparseStalePolls: computed(() => 0),
refreshReparseProgress: vi.fn(),
}),
}));
@@ -196,10 +220,15 @@ vi.mock('@/features/chat/components/shipping-review/ReviewDocumentEvidenceDrawer
vi.mock('../components/shipping-review/ReviewBuildEligibilitySummary.vue', () => ({
default: {
name: 'ReviewBuildEligibilitySummary',
emits: ['open-details'],
props: ['eligibility', 'exceptionCount', 'exceptionOrdinal'],
emits: ['open-details', 'navigate-exception'],
template:
'<div data-testid="mock-eligibility-summary">'
+ '<button data-testid="review-open-eligibility-details" @click="$emit(\'open-details\')">详情</button>'
+ '<div v-if="exceptionCount" data-testid="review-exception-nav">'
+ '<button data-testid="review-exception-prev" @click="$emit(\'navigate-exception\', -1)">上一</button>'
+ '<button data-testid="review-exception-next" @click="$emit(\'navigate-exception\', 1)">下一</button>'
+ '</div>'
+ '</div>',
},
}));
@@ -314,6 +343,8 @@ async function mountView() {
confirmCreate: '确认并建单',
restoreMachine: '恢复',
moreFields: '更多 {count}',
moreLineFields: '更多列 {count}',
collapseFields: '收起',
addLine: '新增行',
emptyValue: '空',
valueSources: { machine: '系统' },
@@ -360,6 +391,11 @@ async function mountView() {
saveFailed: '失败',
versionConflict: { badge: '冲突' },
statusBanner: { unknown: '未知' },
reparseFailedVersion: {
notice: 'V{failedVersion} 重新识别失败,失败阶段:{stage}。当前展示并可继续复核:V{displayedVersion}。',
unknownStage: '未知阶段',
stages: { layout_parsing: '解析 PDF 页面与表格' },
},
reparseProgress: {
title: '重识别',
subtitle: '',
@@ -451,6 +487,40 @@ describe('ShippingOrderReviewView layout phase 1', () => {
beforeEach(() => {
vi.clearAllMocks();
resetActiveCaseFixture();
workItem.value = null;
});
it('shows restored version as current and latest version only as failed attempt', async () => {
workItem.value = {
item_no: 'WFI-1',
current_version_no: 4,
lifecycle_status: 'reparse_failed',
displayed_version: { version_no: 3, run_no: 'RUN-3', case_no: 'CASE-1', status: 'restored' },
latest_attempt: {
version_no: 4,
run_no: 'RUN-4',
status: 'failed',
failure_stage: 'layout_parsing',
error_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
},
};
const wrapper = await mountView();
const notice = wrapper.find('[data-testid="review-reparse-failed-version-notice"]');
expect(notice.text()).toContain('V4 重新识别失败');
expect(notice.text()).toContain('解析 PDF 页面与表格');
expect(notice.text()).toContain('V3');
// 关键断言:顶栏当前版本跟随旧成功结果 V3,禁止把旧字段标成失败尝试 V4。
expect(wrapper.text()).toContain('WFI-1');
expect(wrapper.text()).toContain('V3');
});
it('does not show reparse-failure version notice for normal review', async () => {
workItem.value = {
item_no: 'WFI-1', current_version_no: 3, lifecycle_status: 'pending_review',
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-reparse-failed-version-notice"]').exists()).toBe(false);
});
it('renders main editor + summary rail without chat context toggle', async () => {
@@ -459,7 +529,8 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-main-editor"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-build-gate-rail"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-document-navigation"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="review-workbench-mode"]').exists()).toBe(true);
// 标准复核不展示仅含标题的空模式条,避免占用主编辑区高度。
expect(wrapper.find('[data-testid="review-workbench-mode"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('对话上下文');
expect(wrapper.html()).not.toContain('showContext');
expect(wrapper.html()).not.toContain('hideContext');
@@ -476,6 +547,15 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(true);
});
it('renders empty optional schema fields as editable line columns', async () => {
const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
// 关键断言:库存源线索即使非必填且尚无机器值,也必须作为 Schema 列显示并可编辑。
expect(wrapper.text()).toContain('库存源线索');
expect(inputs).toHaveLength(1);
expect(inputs[0].attributes('disabled')).toBeUndefined();
});
it('does not render resident AI card without focused field', async () => {
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-llm-field-entry"]').exists()).toBe(false);
@@ -512,7 +592,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-document-evidence-drawer"]').exists()).toBe(true);
});
it('navigates exception fields from draft issues banner', async () => {
it('navigates exception fields from the summary rail', async () => {
activeCase.value = {
...activeCase.value,
draft: {
File diff suppressed because it is too large. Load diff