refactor(shipping-notice): 重构货代发货通知状态管理,移除废弃的process_status字段

统一货代发货通知的业务阶段为四个标准阶段:接收解析、订单复核、发货准备、上传完成
设置 ui_state 为前端唯一状态数据源,不再依赖 process_status 驱动业务流程
删除 shipping_notices 表的废弃 process_status 列及对应复合索引,新增数据库迁移脚本
替换全栈代码中所有对 process_status 的引用为生命周期、上传状态等领域字段
更新相关文档、测试用例与前端展示逻辑适配新的状态管理规则
This commit is contained in:
hugo committed 2026-08-15 10:19:10 +08:00
1 parent 6684e7181a
commit 5ef8329bd8
178 files changed
+5091 -1734

No files matched your search

@@ -48,6 +48,7 @@ const {
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
compactShippingProgress?: boolean;
}>();
const emit = defineEmits<{
@@ -61,6 +62,7 @@ const emit = defineEmits<{
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
}>();
const bindScrollContainer = (node: unknown) => {
@@ -166,6 +168,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
:training-handlers="trainingHandlers"
:compact-shipping-progress="compactShippingProgress"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@@ -174,6 +177,7 @@ const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
@maintenance-edit-record="emit('maintenance-edit-record', $event)"
@maintenance-view-record-history="emit('maintenance-view-record-history', $event)"
@maintenance-create-record-for-device="emit('maintenance-create-record-for-device', $event)"
@open-batch-workbench="emit('open-batch-workbench')"
/>
<ToolRunProgressCard
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg, index)"
@@ -88,7 +88,8 @@ const route = useRoute();
const shippingProcessing = useShippingNoticeWorkflow({
// 历史会话首屏直接使用路由 ID,与聊天消息并行拉取统一进度。
conversationId: () => page.conversationId || String(route.query.conversation_id || ''),
// 路由切换先于 page 历史消息回填;必须先切换 Projection,禁止短暂复用旧会话卡片。
conversationId: () => String(route.query.conversation_id || page.conversationId || ''),
refreshTrigger: () => page.workflowRefreshTrigger,
});
provide(SHIPPING_WORKFLOW_KEY, shippingProcessing);
@@ -151,13 +152,39 @@ const activeExtractionRunNo = computed(() => {
});
/** 批次进度工作台按需打开;关闭时不占用对话区右侧布局。 */
const batchWorkbenchOpen = ref(false);
const showShippingWorkflowTimeline = computed(() => (
page.isShippingNoticeAgent
&& batchWorkbenchOpen.value
&& Boolean(page.conversationId || activeExtractionRunNo.value)
));
const compactShippingProgress = computed(() => batchWorkbenchOpen.value);
function openBatchWorkbench() {
batchWorkbenchOpen.value = true;
}
function closeBatchWorkbench() {
batchWorkbenchOpen.value = false;
}
/**
* 批次中心只服务于用户主动打开时所在的会话。切换历史会话或 Agent 后必须关闭,
* 否则旧会话的右侧投影会短暂占用新会话的对话区并造成“本次处理”串批错觉。
*/
watch(
() => [String(page.conversationId || ''), Number(page.currentAgentId || 0)] as const,
(next, previous) => {
if (!previous || next[0] === previous[0] && next[1] === previous[1]) return;
batchWorkbenchOpen.value = false;
},
);
const embeddedIframeSrc = computed(() => {
const agent = page.currentAgent;
@@ -480,9 +507,9 @@ watch(() => page.currentAgentId, () => {
<ShippingOrderReviewView v-if="isOrderReviewMode" />
<div v-else class="flex min-h-0 min-w-0 flex-1">
<div v-else class="flex min-h-0 min-w-0 flex-1" :class="showShippingWorkflowTimeline ? 'shipping-workbench-layout' : ''">
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
<div class="flex min-h-0 min-w-0 flex-1 flex-col" :class="showShippingWorkflowTimeline ? 'shipping-chat-column' : ''">
<TrainingWorkspacePanel
@@ -560,6 +587,8 @@ watch(() => page.currentAgentId, () => {
:scroll-container-holder="page.scrollContainerHolder"
:compact-shipping-progress="compactShippingProgress"
@copy="page.copyToClipboard($event.message, $event.index)"
@edit="page.input = $event"
@@ -580,6 +609,8 @@ watch(() => page.currentAgentId, () => {
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
@open-batch-workbench="openBatchWorkbench"
/>
@@ -666,6 +697,8 @@ watch(() => page.currentAgentId, () => {
:conversation-id="page.conversationId"
:refresh-trigger="page.workflowRefreshTrigger"
:controller="shippingProcessing"
@close="closeBatchWorkbench"
/>
@@ -816,3 +849,16 @@ watch(() => page.currentAgentId, () => {
</template>
<style scoped>
/** 打开批次工作台后,左侧对话保留为压缩入口,右侧取得主工作区宽度。 */
@media (min-width: 1024px) {
.shipping-workbench-layout {
min-width: 0;
}
.shipping-chat-column {
flex: 0 0 clamp(360px, 32vw, 520px);
}
}
</style>
@@ -1,6 +1,6 @@
/**
* features/chat/components/ShippingWorkflowStepper.vue
* 用途:货代发货七步流程 Stepper 展示组件。
* 用途:货代发货四阶段 Stepper 展示组件。
* 依赖:shipping/shippingStepper、vue-i18n。
* 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。
*/
@@ -33,7 +33,7 @@ const dotClass = (status: ShippingWorkflowStepItem['status']) => {
<template>
<div class="space-y-2">
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4 xl:grid-cols-7' : 'md:grid-cols-4 xl:grid-cols-7'">
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4' : 'md:grid-cols-4'">
<div
v-for="(step, index) in steps"
:key="step.id"
@@ -72,6 +72,7 @@ const {
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMessageHandlers;
trainingHandlers: TrainingHandlers;
compactShippingProgress?: boolean;
}>();
const emit = defineEmits<{
@@ -83,6 +84,7 @@ const emit = defineEmits<{
'maintenance-edit-record': [record: MaintenanceRecord];
'maintenance-view-record-history': [device: MaintenanceDevice];
'maintenance-create-record-for-device': [device: MaintenanceDevice];
'open-batch-workbench': [];
}>();
const authStore = useAuthStore();
@@ -712,7 +714,9 @@ function handleInlineDownload(file: InlineDownloadFile): void {
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: isContractReviewMessage
? 'w-full'
: 'chat-msg-assistant'"
: shippingOrderExtractionState
? 'w-full'
: 'chat-msg-assistant'"
>
<template v-if="message.role === 'user'">
<ChatMessageAttachmentList
@@ -731,9 +735,11 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:retrying="retryingOrderExtraction"
:refreshing="refreshingOrderExtraction"
:cancelling="cancellingOrderExtraction"
:compact-progress="compactShippingProgress"
@retry="retryShippingOrderExtraction"
@refresh="refreshShippingOrderExtraction"
@cancel="cancelShippingOrderExtraction"
@open-batch-workbench="emit('open-batch-workbench')"
/>
<LeaveMessageBlock
v-if="isLeaveMessage"
@@ -44,6 +44,7 @@ const props = defineProps<{
docked: boolean;
floatSide: 'right' | 'left';
src: string;
emailPreview?: { document_id: number; filename: string; text: string } | null;
evidence: ShippingOrderReviewEvidence | null;
evidenceList: ShippingOrderReviewEvidence[];
fieldLabel?: string;
@@ -729,8 +730,11 @@ onBeforeUnmount(() => {
</div>
<div class="grid min-h-0 flex-1 grid-rows-[minmax(0,1fr)_auto]">
<div v-if="emailPreview" class="min-h-0 overflow-auto whitespace-pre-wrap p-4 font-mono text-xs leading-6 text-slate-700 dark:text-slate-200" data-testid="review-email-evidence-preview">
{{ emailPreview.text }}
</div>
<ReviewDocumentPreview
v-if="src"
v-else-if="src"
class="min-h-0"
:src="src"
:evidence="evidence"
@@ -172,7 +172,7 @@ defineExpose({
{{ t('chat.shippingNoticeDuplicateMatchTask', { taskNo: primaryMatch.task_no }) }}
</div>
<div class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.process_status }) }}
{{ t('chat.shippingNoticeDuplicateMatchStatus', { status: primaryMatch.lifecycle || 'active' }) }}
</div>
<div v-if="primaryMatch.matched_fields?.length" class="mt-0.5 text-muted">
{{ t('chat.shippingNoticeDuplicateMatchFields', { fields: primaryMatch.matched_fields.join(', ') }) }}
@@ -1,6 +1,6 @@
/**
* features/chat/components/shipping/ShippingConversationProcessingCard.vue
* 用途:右侧「本次处理中」顶层任务卡——needs_action / processing / 处理记录。
* 用途:右侧「批次进度中心」顶层任务卡——needs_action / processing / 处理记录。
* 依赖:vue-i18n、ConversationProcessingProjection、conversationProcessingState、
* conversationProcessingDisplay、actionPresentation、shippingProcessingLabels、SidebarProgressInline。
* 逻辑:由 ShippingWorkflowTimeline 嵌入;只消费统一 projection / workItems;
@@ -33,7 +33,8 @@ import {
resolveShippingProcessingStatusLabel,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import { resolveConversationTaskActionPresentation } from '@/features/shipping-progress/actionPresentation';
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
import SidebarProgressInline from '@/features/shipping-progress/components/SidebarProgressInline.vue';
import type { ActionPresentation, ActionPresentationItem } from '@/features/shipping-progress/types';
@@ -45,6 +46,8 @@ const props = defineProps<{
conversationId?: string | null;
/** 后端截断提示:history 还有未返回内容时在处理记录底部展示 */
hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean;
}>();
const emit = defineEmits<{
@@ -65,6 +68,17 @@ const uiState = createConversationProcessingUiState();
/** 处理记录整组默认折叠。 */
const historySectionExpanded = ref(false);
/** 批次中心文件叶子行;EML 仅是聚合容器,文件状态、原因与动作必须取叶子自身投影。 */
type WorkbenchFileRow = {
kind: 'document';
object_key: string;
label: string;
filename?: string | null;
document_id?: number | null;
status_label?: string | null;
projection?: ShippingProcessingProjection;
};
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
props.projection || null
@@ -185,6 +199,7 @@ function canExpandFileDetails(task: ConversationProcessingUserTask): boolean {
* 处理记录(completed/history)永不展实时进度。
*/
function progressModeForTask(task: ConversationProcessingUserTask): 'full' | 'compact' | 'hidden' {
if (props.workbenchMode) return 'hidden';
if (!projectionForTask(task)) return 'hidden';
const group = String(task.group || '').trim();
if (group === 'completed' || group === 'history') return 'hidden';
@@ -202,6 +217,137 @@ function taskLabel(_task: ConversationProcessingUserTask): string {
return t('chat.shippingProcessing.multiPdfTaskTitle');
}
/** EML 聚合标题优先使用后端邮件文件名,普通文件则显示主文件名。 */
function groupTitle(task: ConversationProcessingUserTask): string {
const projection = projectionForTask(task);
const children = task.aggregateChildren || [];
const projectionFilename = String(projection?.sourceSummary?.filename || '').trim();
const emlChild = children.find((child) => (
String(child.sourceSummary?.filename || '').trim().toLowerCase().endsWith('.eml')
));
const emailChild = children.find((child) => Boolean(child.sourceSummary?.emailSubject));
const isEml = projection?.sourceType === 'eml'
&& Boolean(
emlChild
|| emailChild
|| projection?.sourceSummary?.emailSubject
|| projectionFilename.toLowerCase().endsWith('.eml'),
);
if (!isEml) return projection?.sourceSummary?.filename || task.title || taskLabel(task);
// 后端在 EML 聚合根 sourceSummary 写入 Intake 原始邮件资产名;子附件列表不含
// 邮件本体时仍必须显示该 .eml,不能回退成 Intake 编号或任一 PDF 文件名。
if (projectionFilename.toLowerCase().endsWith('.eml')) return projectionFilename;
if (emlChild?.sourceSummary?.filename) return emlChild.sourceSummary.filename;
if (projection?.sourceSummary?.emailSubject) return `EML · ${projection.sourceSummary.emailSubject}`;
if (emailChild?.sourceSummary?.emailSubject) return `EML · ${emailChild.sourceSummary.emailSubject}`;
if (task.aggregateSummary?.intakeNo) {
return `EML · ${task.aggregateSummary?.intakeNo || task.user_task_no}`;
}
return task.title || taskLabel(task);
}
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const children = task.aggregateChildren || [];
if (children.length) {
return flattenBusinessFileProjections(children).map((child, index) => {
const filename = String(child.sourceSummary?.filename || '').trim();
const documentId = Number(child.sourceSummary?.documentId || 0) || 0;
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${task.user_task_no}-aggregate-${child.workItemNo || index}`,
label: filename || child.workItemNo || `文件 ${index + 1}`,
filename: filename || child.workItemNo || `文件 ${index + 1}`,
status_label: String(child.uiState?.status || child.userStatus || child.status || ''),
projection: child,
};
});
}
const documents = (task.objects || []).filter((item) => (
item.kind === 'document'
&& !String(item.filename || item.label || '').trim().toLowerCase().endsWith('.eml')
));
if (documents.length) {
// direct_pdf 没有 EML aggregate_children;将唯一根 work_item 绑定到其文件行,
// 使状态、原因和操作仍然来自同一份后端 ui_state,而不是丢失操作或回退 legacy 字段。
const directFileProjection = projectionForTask(task);
return documents.map((item) => ({
kind: 'document' as const,
object_key: item.object_key,
label: item.label,
filename: item.filename,
document_id: item.document_id,
status_label: item.status_label,
projection: directFileProjection?.sourceType === 'direct_pdf'
? directFileProjection
: undefined,
}));
}
const taskName = String(task.title || '').trim().toLowerCase();
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
return (task.document_names || []).map((filename, index) => ({
kind: 'document' as const,
object_key: `${task.user_task_no}-document-${index}`,
label: filename,
filename,
status_label: task.status_label,
}));
}
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
const seen = new Set<string>();
return tasks.reduce((total, task) => total + workbenchFileRows(task).reduce((count, file) => {
const filename = String(file.filename || file.label || '').trim().toLowerCase();
if (filename.endsWith('.eml')) return count;
const key = String(('document_id' in file ? file.document_id : undefined)
|| file.object_key || file.filename || file.label || '').trim();
if (!key || seen.has(key)) return count;
seen.add(key);
return count + 1;
}, 0), 0);
}
function workbenchFileStatus(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
const status = file.projection
? (file.projection.uiState?.status || file.projection.userStatus || file.projection.status)
: (file.status_label || task.status_label || '');
return resolveShippingProcessingStatusLabel(String(status), te, t);
}
function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
if (file.projection) {
const reason = file.projection.uiState
? file.projection.uiState.blocking_reason
: file.projection.blockingReason;
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
return key && te(key) ? t(key) : String(reason.code || '').trim();
}
return taskReasonLabel(task);
}
/** 附件阶段来自叶子 ui_state;EML 父阶段只适用于 EML 卡,不得复制到不同状态的附件。 */
function workbenchFileStage(file: WorkbenchFileRow, task: ConversationProcessingUserTask): string {
const stage = file.projection
? (file.projection.uiState?.stage || file.projection.userStage || file.projection.stage)
: stageLabel(task);
const key = shippingProcessingStageKey(String(stage || ''));
return key && te(key) ? t(key) : String(stage || '');
}
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
function filePrimaryActionItem(file: WorkbenchFileRow): ActionPresentationItem | null {
return file.projection
? resolveProcessingActionPresentation(file.projection, { surface: 'right' }).primary
: null;
}
function onFileProjectionAction(file: WorkbenchFileRow) {
const action = filePrimaryActionItem(file);
if (file.projection && action) emit('projectionAction', { projection: file.projection, item: action });
}
/**
* 主文件副标题:有主文件名时渲染「主文件:{name}」。
*/
@@ -227,7 +373,11 @@ function fileCountLabel(task: ConversationProcessingUserTask): string {
* 任务状态文案:优先统一 shippingProcessing,回退 shippingWorkflow。
*/
function statusLabel(task: ConversationProcessingUserTask): string {
return resolveShippingProcessingStatusLabel(String(task.status_label || ''), te, t);
return resolveShippingProcessingStatusLabel(
String(task.uiState?.status || task.userStatus || task.status_label || ''),
te,
t,
);
}
/** 展示统一投影的真实履约阶段;识别候选不再冒充最终完成。 */
@@ -237,17 +387,16 @@ function stageLabel(task: ConversationProcessingUserTask): string {
return intakeStageLabel(projection);
}
/** 展示后端统一投影的阻断/失败原因,不从状态码自行猜测。 */
/** 展示后端 ui_state 已裁决的阻断原因;i18n 仅负责翻译,不映射或猜测业务原因。 */
function taskReasonLabel(task: ConversationProcessingUserTask): string {
const code = String(task.blockingReason?.code || task.aggregateSummary?.reasonCodes[0] || '').trim();
if (!code) return '';
const messages: Record<string, string> = {
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
};
return messages[code] || '文件处理需要人工确认,请进入订单处理查看。';
const reason = task.uiState
? task.uiState.blocking_reason
: task.blockingReason;
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
if (key && te(key)) return t(key);
// 未升级响应没有 i18n_key 时仅透传后端原因码,不根据文件名、状态或动作伪造说明。
return String(reason.code || '').trim();
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
@@ -300,10 +449,14 @@ function currentNeedLabel(task: ConversationProcessingUserTask): string {
primaryAction?: { code?: string } | null;
};
const action = String(
typedTask.primaryAction?.code
?? task.primary_action
?? task.available_actions?.[0]
?? '',
task.uiState
? (task.uiState.primary_action?.code
?? task.uiState.secondary_actions.find((item) => item.enabled)?.code
?? '')
: (typedTask.primaryAction?.code
?? task.primary_action
?? task.available_actions?.[0]
?? ''),
).trim().toLowerCase();
const labels: Record<string, string> = {
confirm_customer: 'chat.shippingProcessing.currentNeed.confirmCustomer',
@@ -356,6 +509,7 @@ function shouldShowOverflowActions(_task: ConversationProcessingUserTask): boole
* 是否渲染任务级主/次动作区(不含「展开文件详情」文件控制)。
*/
function shouldShowTaskLevelActions(task: ConversationProcessingUserTask): boolean {
if (props.workbenchMode) return Boolean(primaryActionItem(task));
if (projectionForTask(task)) return false;
return Boolean(primaryActionItem(task) || secondaryActionItem(task));
}
@@ -441,7 +595,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-group-failed"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.groupFailed', { count: failedTasks.length }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(failedTasks) }) }}
</div>
<div class="space-y-2">
<article
@@ -463,15 +617,13 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
{{ workbenchMode ? groupTitle(task) : 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">
<div v-if="!workbenchMode" 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="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div
v-if="primaryFileLabel(task)"
v-if="!workbenchMode && primaryFileLabel(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-primary-file"
>
@@ -496,15 +648,18 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div
v-if="task.group === 'needs_action' && currentNeedLabel(task)"
class="mt-1 text-[11px] text-secondary"
data-testid="shipping-processing-current-need"
>
{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-rose-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
</div>
<span class="shrink-0 rounded-full bg-rose-100 px-2 py-0.5 text-[11px] font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-rose-300 px-2.5 py-1 text-[11px] font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
</div>
</div>
<SidebarProgressInline
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
class="mt-1.5 border-t border-current/10 pt-1.5"
:projection="projectionForTask(task)!"
:compact="progressModeForTask(task) === 'compact'"
@@ -516,7 +671,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-task-actions"
>
<button
v-if="!projectionForTask(task) && primaryActionItem(task)"
v-if="(!workbenchMode && !projectionForTask(task)) && primaryActionItem(task)"
type="button"
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
@@ -535,7 +690,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-group-waiting_human"
>
<div class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300">
{{ t('chat.shippingProcessing.groupWaitingHuman', { count: waitingHumanTasks.length }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(waitingHumanTasks) }) }}
</div>
<div class="space-y-2">
<article
@@ -546,23 +701,38 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
: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">
<div class="text-sm font-semibold text-primary">{{ workbenchMode ? groupTitle(task) : resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}</div>
<div v-if="!workbenchMode" 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="stageLabel(task)">· {{ stageLabel(task) }}</span>
</div>
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">{{ taskReasonLabel(task) }}</div>
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
</button>
<div v-if="currentNeedLabel(task)" class="mt-1 text-[11px] text-secondary">{{ t('chat.shippingProcessing.progress.currentNeedLabel') }}{{ currentNeedLabel(task) }}</div>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-amber-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-white/70 px-2 py-2 dark:bg-slate-950/30">
<div class="min-w-0 flex-1">
<div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div>
<div v-if="workbenchFileReason(file, task)" class="mt-0.5 truncate text-[11px] text-rose-600 dark:text-rose-300">{{ workbenchFileReason(file, task) }}</div>
</div>
<span class="shrink-0 rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
</div>
</div>
<SidebarProgressInline
v-if="projectionForTask(task)"
v-if="!workbenchMode && projectionForTask(task)"
class="mt-1.5 border-t border-current/10 pt-1.5"
:projection="projectionForTask(task)!"
:compact="false"
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
/>
<button
v-if="!workbenchMode && primaryActionItem(task)"
type="button"
class="mt-2 rounded-md bg-brand-600 px-2.5 py-1.5 text-[11px] font-medium text-white hover:bg-brand-700"
@click="onTaskAction(task, primaryActionItem(task)!.actionCode)"
>
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
</button>
</article>
</div>
</section>
@@ -572,7 +742,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
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: processingTasks.length }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(processingTasks) }) }}
</div>
<div class="space-y-2">
<article
@@ -591,14 +761,13 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@click="onSelectTask(task)"
>
<div class="text-sm font-semibold text-primary">
{{ resolveShippingProcessingMessage('taskTitle', te, t, { label: taskLabel(task) }) }}
{{ workbenchMode ? groupTitle(task) : 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">
<div v-if="!workbenchMode" 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>
</div>
<div
v-if="primaryFileLabel(task)"
v-if="!workbenchMode && primaryFileLabel(task)"
class="mt-0.5 truncate text-[11px] text-muted"
data-testid="shipping-processing-task-primary-file"
>
@@ -620,8 +789,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
{{ resolveShippingProcessingMessage('justCreated', te, t) }}
</div>
</button>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-sky-200/70 pt-2">
<div v-for="file in workbenchFileRows(task)" :key="file.object_key" class="flex items-center gap-3 rounded-md bg-surface-muted/40 px-2 py-2">
<div class="min-w-0 flex-1"><div class="truncate text-xs font-medium text-primary">{{ file.filename || file.label }}</div><div class="mt-0.5 text-[11px] text-secondary">{{ workbenchFileStage(file, task) || t('chat.shippingProcessing.batchWorkbench.fileProcessing') }}</div></div>
<span class="shrink-0 rounded-full bg-sky-100 px-2 py-0.5 text-[11px] font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="shrink-0 rounded-md border border-brand-300 px-2.5 py-1 text-[11px] font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
</div>
</div>
<SidebarProgressInline
v-if="progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
v-if="!workbenchMode && progressModeForTask(task) !== 'hidden' && projectionForTask(task)"
class="mt-1.5 border-t border-current/10 pt-1.5"
:projection="projectionForTask(task)!"
:compact="progressModeForTask(task) === 'compact'"
@@ -633,7 +809,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-task-actions"
>
<button
v-if="!projectionForTask(task) && primaryActionItem(task)"
v-if="!workbenchMode && !projectionForTask(task) && primaryActionItem(task)"
type="button"
class="rounded-md border border-brand-300 bg-brand-600 px-2.5 py-1 text-[11px] font-medium text-white hover:bg-brand-700 dark:border-brand-700 dark:bg-brand-700 dark:hover:bg-brand-600"
:data-testid="`shipping-processing-action-${primaryActionItem(task)!.actionCode}`"
@@ -53,6 +53,40 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
});
describe('ShippingOrderExtractionCard', () => {
it('opens the authoritative conversation batch even when no single run number is available', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState() },
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'INTAKE:SNI-BATCH', title: 'batch.eml', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: [],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
});
it('collapses file-level progress when the batch workbench is open', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: { processingWorkItems: ref([]) } } },
});
expect(wrapper.find('[data-testid="shipping-order-extraction-status-groups"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(false);
});
it('uses unified EML aggregation and keeps candidate creation out of completed', async () => {
const aggregate = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-1', sourceType: 'eml', rootOrderTaskNo: 'OT-1',
@@ -99,13 +133,61 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-aggregate"]').text()).toContain('stable.eml');
});
it('does not render a historical EML snapshot while the authoritative conversation projection is loading', () => {
const historicalAggregate = {
workItemType: 'order_task', workItemNo: 'INTAKE:SNI-HISTORY', sourceType: 'eml', intakeNo: 'SNI-HISTORY',
sourceSummary: { filename: 'historical.eml', documentCount: 3 },
aggregateSummary: { intakeNo: 'SNI-HISTORY', total: 3, completed: 0, processing: 3, needsAction: 0, failed: 0, stages: [], reasonCodes: [] },
aggregateChildren: [],
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-HISTORY' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref(null),
processingWorkItems: ref([historicalAggregate]),
initialLoading: ref(true),
loading: ref(true),
} } },
});
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-aggregate"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-projection-loading"]').exists()).toBe(true);
expect(wrapper.text()).not.toContain('historical.eml');
expect(wrapper.text()).not.toContain('系统处理中');
});
it('does not render message document rows while the authoritative projection is loading', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState({
documents: [{
unitId: 91,
documentId: 191,
documentType: 'attachment',
fileName: 'message-snapshot.pdf',
status: 'review_required',
}],
}) },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref(null),
processingWorkItems: ref([]),
initialLoading: ref(true),
loading: ref(true),
} } },
});
expect(wrapper.text()).not.toContain('message-snapshot.pdf');
expect(wrapper.text()).not.toContain('系统处理中');
});
it('expands an EML inside its status group and shows every child attachment state', async () => {
const child = {
workItemType: 'order_task', workItemNo: 'OT-CHILD-1', sourceType: 'eml', rootOrderTaskNo: 'OT-ROOT',
shippingNoticeNo: null, runNo: 'SNER-DETAIL', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-DETAIL',
status: 'failed', stage: 'document_parsing', progressVersion: 1, lastActivityAt: '', currentGate: null, availableActions: [],
sourceSummary: { emailSubject: null, filename: 'failed.pdf', documentCount: 1, parsedDocumentCount: 0, candidateCount: 0, customerName: null, poNumber: null },
childOrderTasks: [], userStatus: 'failed', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
childOrderTasks: [], userStatus: 'running', userStage: 'document_parsing', facts: { uploadState: 'not_created' },
// 后端新裁决与旧 userStatus 冲突时,摘要卡必须使用 ui_state,不能显示成“处理中”。
uiState: { status: 'failed', stage: 'document_parsing', blocking_reason: { code: 'PARSE_FAILED' }, primary_action: null, secondary_actions: [] },
blockingReason: { code: 'PARSE_FAILED' },
} as any;
const task = { user_task_no: 'INTAKE:SNI-DETAIL', title: 'mail.eml', file_count: 1, userGroup: 'failed', group: 'needs_action', aggregateChildren: [child], aggregateSummary: { intakeNo: 'SNI-DETAIL', total: 1, completed: 0, processing: 0, needsAction: 0, failed: 1, stages: ['document_parsing'], reasonCodes: ['PARSE_FAILED'] } } as any;
@@ -126,9 +208,11 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('文件处理需要人工确认');
expect(wrapper.text()).not.toContain('PARSE_FAILED');
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-OT-CHILD-1"]')
.classes()).toContain('text-rose-600');
});
it('falls back to the matched work item children when the status task only has a summary', async () => {
it('does not supplement an authoritative EML group from a second work-item snapshot', async () => {
const child = {
workItemType: 'order_task', workItemNo: 'OT-FALLBACK-1', sourceType: 'eml', rootOrderTaskNo: 'OT-FALLBACK',
shippingNoticeNo: null, runNo: 'SNER-FALLBACK', caseNo: null, conversationId: 'conv-1', submissionNo: 'SOS-1', intakeNo: 'SNI-FALLBACK',
@@ -145,7 +229,32 @@ describe('ShippingOrderExtractionCard', () => {
} } },
});
await wrapper.get('[data-testid="shipping-order-extraction-eml-processing-INTAKE:SNI-FALLBACK"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('inside.eml.pdf');
// 状态组出现后,子文件必须完全来自该组;不能用另一份 work_items 补数。
expect(wrapper.find('[data-testid="shipping-order-extraction-eml-children"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('inside.eml.pdf');
});
it('uses the conversation projection total instead of the message Run snapshot total', () => {
const task = {
user_task_no: 'INTAKE:SNI-TOTAL', title: 'mail-total.eml', file_count: 2,
userGroup: 'waiting_human', group: 'needs_action', aggregateChildren: [],
aggregateSummary: { intakeNo: 'SNI-TOTAL', total: 2, completed: 0, processing: 0, needsAction: 2, failed: 0, stages: ['order_review'], reasonCodes: [] },
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState({ summary: { ...buildState().summary, totalDocuments: 6 } }), runNo: 'SNER-TOTAL' },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
summary: { total_files: 2, completed_files: 0, waiting_human_files: 2, failed_files: 0 },
ui_state: { status: 'waiting_human' },
status_groups: { failed: [], waiting_human: [task], processing: [], completed: [], cancelled: [], archived: [] },
}),
processingWorkItems: ref([{ sourceType: 'eml', intakeNo: 'SNI-TOTAL', aggregateChildren: [{ sourceSummary: { filename: 'stale.pdf' } }] }]),
} } },
});
expect(wrapper.text()).toContain('共 2 个文件');
expect(wrapper.text()).not.toContain('共 6 个文件');
expect(wrapper.text()).not.toContain('stale.pdf');
});
it('counts unique EML attachment children instead of task rows', async () => {
@@ -481,7 +590,7 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
});
it('shows continue CTA for review-required without retry', () => {
it('keeps only the batch workbench CTA for review-required without retry', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
@@ -511,8 +620,9 @@ describe('ShippingOrderExtractionCard', () => {
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
expect(wrapper.text()).not.toContain('重试解析');
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-view-details"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
});
it('does not render multi-OT ChatProgressSummary list', () => {
@@ -576,10 +686,10 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.findAll('[data-testid="chat-progress-summary-list"]').length).toBe(0);
expect(wrapper.text()).not.toContain('PO.pdf');
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('继续处理');
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('emits retry for failed attachments via primary CTA', async () => {
it('keeps retry actions out of the bottom action bar', async () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
@@ -599,13 +709,11 @@ describe('ShippingOrderExtractionCard', () => {
},
global: { plugins: [i18n] },
});
const retryBtn = wrapper.find('[data-testid="shipping-order-extraction-primary-action"]');
expect(retryBtn.text()).toContain('重试解析');
await retryBtn.trigger('click');
expect(wrapper.emitted('retry')?.length).toBe(1);
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
});
it('keeps view details as secondary text link only', () => {
it('does not render the removed view details link', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
@@ -617,8 +725,7 @@ describe('ShippingOrderExtractionCard', () => {
global: { plugins: [i18n] },
});
const details = wrapper.find('[data-testid="shipping-order-extraction-view-details"]');
expect(details.exists()).toBe(true);
expect(details.classes().join(' ')).toContain('underline-offset-2');
expect(details.exists()).toBe(false);
expect(wrapper.findAll('[data-testid="shipping-order-extraction-primary-action"]').length).toBe(0);
});
});
@@ -2,7 +2,7 @@
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区「订单识别任务」摘要卡——标题、文件数+状态、一行 handling 摘要、唯一主 CTA、查看详情。
* 依赖:订单抽取 Run 状态卡 DTO、shipping.api 文档/进度接口、ShippingOrderExtractionDetailsDrawer、vue-router、vue-i18n。
* 逻辑:对话区只做任务摘要;长进度/Gate/刷新取消由右侧栏承接;详情抽屉仅由次要「查看详情」打开。
* 逻辑:对话区默认展示状态-EML 聚合;批次工作台打开后切换为紧凑摘要,长进度/Gate/刷新取消由工作台承接。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
@@ -38,12 +38,15 @@ const props = defineProps<{
readonlyReason?: string | null;
/** 可选统一投影;摘要卡不再渲染进度,仅保留 prop 兼容宿主。 */
processingProjection?: ShippingProcessingProjection | null;
/** 批次工作台打开时,左侧只保留摘要,避免与工作台重复展示文件明细。 */
compactProgress?: boolean;
}>();
const emit = defineEmits<{
retry: [];
refresh: [];
cancel: [reason?: string];
'open-batch-workbench': [];
}>();
const { t, te } = useI18n();
@@ -52,7 +55,14 @@ const router = useRouter();
const shippingWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
type ConversationStatusGroups = NonNullable<import('../../types/shipping.api.types').ConversationProcessingProjection['status_groups']>;
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => ((shippingWorkflow as { processing?: { value?: { status_groups?: ConversationStatusGroups | null } | null } } | null)?.processing?.value?.status_groups || null));
type ConversationProcessing = import('../../types/shipping.api.types').ConversationProcessingProjection;
const conversationProcessing = computed<ConversationProcessing | null>(() => (
(shippingWorkflow as { processing?: { value?: ConversationProcessing | null } | null } | null)?.processing?.value || null
));
const conversationProjectionLoading = computed(() => Boolean(
(shippingWorkflow as { initialLoading?: { value?: boolean } | null } | null)?.initialLoading?.value,
));
const conversationStatusGroups = computed<ConversationStatusGroups | null>(() => conversationProcessing.value?.status_groups || null);
const hasConversationStatusGroups = computed(() => Boolean(conversationStatusGroups.value));
const statusGroupDefs = [
{ key: 'failed', label: 'chat.shippingProcessing.groupFailed' },
@@ -83,6 +93,9 @@ function toggleEmlTask(taskNo: string) {
}
function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]; user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
if (task.aggregateChildren?.length) return task.aggregateChildren;
// [AUTHORITY] 新会话投影必须自带 EML 子文件;不能从 Run 快照或另一份 work_items 补齐,
// 否则左右面板会出现不同文件数、不同状态的同一封邮件。
if (hasConversationStatusGroups.value) return [];
const projection = statusTaskProjection(task);
if (!projection) return [];
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
@@ -147,36 +160,55 @@ function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]
} as ShippingProcessingProjection));
}
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const children = taskChildren(task);
// EML 是来源容器;统一只计其附件,避免聊天卡与批次中心相差一份 EML 本体。
const children = taskChildren(task).filter((child) => !String(
child.sourceSummary?.filename || '',
).trim().toLowerCase().endsWith('.eml'));
if (children.length) {
const ids = new Set(children.map((child) => String(child.sourceSummary?.documentId || child.workItemNo || '').trim()).filter(Boolean));
return ids.size || children.length;
}
if (hasConversationStatusGroups.value) return Math.max(0, Number(task.file_count || 0));
const projection = statusTaskProjection(task);
const sourceCount = Number(projection?.sourceSummary?.documentCount || 0);
return sourceCount > 0 ? sourceCount : Math.max(0, Number(task.file_count || 0));
}
function childStatusLabel(child: ShippingProcessingProjection) {
const status = String(child.userStatus || child.status || '').toLowerCase();
const status = displayProjectionStatus(child);
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
}
function userReasonLabel(code?: string | null) {
const key = String(code || '').trim();
const messages: Record<string, string> = {
'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED': '识别结果需要人工确认,请进入订单处理继续。',
'generic_extraction_disabled': '当前文件暂不支持自动解析,请人工处理或更换文件。',
'SHIPPING_NOTICE.INTAKE_PARSE_FAILED': '邮件或附件解析失败,请检查文件后重试。',
'upload_rpa_failed': '上传货代系统失败,请稍后重试。',
};
return messages[key] || (key ? '文件处理需要人工确认,请进入订单处理查看。' : '');
function displayReason(
reason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null,
) {
if (!reason) return '';
const key = String(reason.i18nKey || '').trim();
if (key && te(key)) return t(key);
return String(reason.code || '').trim();
}
/** 新投影有 ui_state 时严格消费其状态;旧响应才回退 userStatus / status。 */
function displayProjectionStatus(item: ShippingProcessingProjection): string {
return String(item.uiState
? item.uiState.status
: (item.userStatus || item.status || '')).trim().toLowerCase();
}
function isFailedProjection(item: ShippingProcessingProjection): boolean {
const status = displayProjectionStatus(item);
return status === 'failed' || status === 'retryable';
}
function isWaitingProjection(item: ShippingProcessingProjection): boolean {
return displayProjectionStatus(item) === 'waiting_human';
}
function isCompletedProjection(item: ShippingProcessingProjection): boolean {
return displayProjectionStatus(item) === 'completed' && item.facts?.uploadState === 'succeeded';
}
function taskReason(task: { uiState?: { blocking_reason: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }; blockingReason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }) {
return task.uiState ? task.uiState.blocking_reason : task.blockingReason;
}
function childStageLabel(child: ShippingProcessingProjection) {
const stage = String(child.userStage || child.stage || '').trim();
if (stage === 'review_required' || stage === 'waiting_review') return '等待人工复核';
if (stage === 'failed' || stage === 'parse_failed') return '处理失败';
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
}
@@ -229,16 +261,22 @@ const lastMatchedEmlAggregate = ref<ShippingProcessingProjection | null>(null);
watch(matchedEmlAggregate, (item) => {
if (item) lastMatchedEmlAggregate.value = item;
}, { immediate: true });
const emlAggregate = computed(() => matchedEmlAggregate.value || lastMatchedEmlAggregate.value);
const emlAggregate = computed(() => (
// [AUTHORITY] 切换会话时先等待该会话的统一投影,禁止旧聊天消息 Run 快照抢占首屏;
// 请求完成后仍只消费后端 Projection,失败则保留既有兼容摘要。
hasConversationStatusGroups.value || conversationProjectionLoading.value
? null
: (matchedEmlAggregate.value || lastMatchedEmlAggregate.value)
));
const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildren || []);
const emlAggregateExpanded = ref(false);
function aggregateStageLabel(item: ShippingProcessingProjection): string {
const stage = String(item.userStage || item.stage || '').trim();
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = String(item.userStatus || item.status || '').trim().toLowerCase();
const status = displayProjectionStatus(item);
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
@@ -315,14 +353,30 @@ const failedRows = computed(() => fileRows.value.filter((row) => (
&& !candidateEmailUnitIds.value.has(row.unitId)
&& !emailRows.value.some((email) => childRows(email).some((child) => child.unitId === row.unitId))
)));
const processedCount = computed(() => emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments));
const processedCount = computed(() => {
if (hasConversationStatusGroups.value) {
const summary = conversationProcessing.value?.summary;
return Math.max(0, Number(summary?.completed_files || 0))
+ Math.max(0, Number(summary?.waiting_human_files || 0))
+ Math.max(0, Number(summary?.failed_files || 0));
}
return emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
});
const progressPercent = computed(() => {
const total = Math.max(0, props.state.summary.totalDocuments);
const total = batchFileCount.value;
return total > 0 ? Math.min(100, Math.round((processedCount.value / total) * 100)) : 0;
});
const completedExpanded = ref(false);
/** 新版会话批次的业务文件数由后端汇总;旧 Run 卡仍保留历史兼容计数。 */
const batchFileCount = computed(() => {
if (hasConversationStatusGroups.value) {
return Math.max(0, Number(conversationProcessing.value?.summary.total_files || 0));
}
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
});
/**
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
*/
@@ -384,6 +438,13 @@ function handlingTitle(item: ShippingOrderExtractionHandlingItemState): string {
* 状态短句:排队/处理中仅「系统处理中」;其余用过程通知,不含文件阶段耗时。
*/
const statusNotice = computed(() => {
if (hasConversationStatusGroups.value) {
const status = String(conversationProcessing.value?.ui_state?.status || '').trim().toLowerCase();
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingSessionSummary.processNoticeFailed');
if (status === 'waiting_human') return t('chat.shippingSessionSummary.processNoticeNeedsAction');
return t('chat.shippingProcessing.systemProcessing');
}
if (emlAggregate.value) {
const status = String(emlAggregate.value.userStatus || '').trim().toLowerCase();
if (status === 'completed') return t('chat.shippingSessionSummary.processNoticeCompleted');
@@ -612,19 +673,36 @@ async function onPrimaryChatAction() {
<template>
<div
v-if="conversationProjectionLoading"
class="mb-3 animate-pulse overflow-hidden rounded-xl border border-slate-200 bg-white/90 shadow-md dark:border-slate-700 dark:bg-slate-900/90"
data-testid="shipping-order-extraction-projection-loading"
>
<!-- 读取权威 Projection 不是业务状态;只显示结构骨架,避免伪造“系统处理中”。 -->
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="h-6 w-36 rounded bg-slate-200 dark:bg-slate-700" />
<div class="mt-3 h-4 w-2/3 rounded bg-slate-200 dark:bg-slate-700" />
<div class="mt-5 h-2 w-full rounded bg-slate-200 dark:bg-slate-700" />
</div>
<div class="space-y-3 p-4">
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
<div class="h-12 rounded-lg bg-slate-100 dark:bg-slate-800" />
</div>
</div>
<div
v-else
class="mb-3 overflow-hidden rounded-xl border border-slate-200 bg-white/90 text-slate-900 shadow-md backdrop-blur-sm dark:border-slate-700 dark:bg-slate-900/90 dark:text-slate-100"
data-testid="shipping-order-extraction-card"
>
<div class="border-b border-slate-200 bg-indigo-50/70 px-5 py-4 dark:border-slate-700 dark:bg-indigo-950/30">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-2 text-lg font-semibold">
<LoaderCircle v-if="emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
<CheckCircle2 v-else-if="emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<LoaderCircle v-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
</div>
<span class="rounded-full bg-slate-200 px-3 py-1 text-xs font-medium text-slate-600 dark:bg-slate-700 dark:text-slate-200">
{{ t('chat.shippingProcessing.batchFilesTotal', { count: emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }) }}
{{ t('chat.shippingProcessing.batchFilesTotal', { count: batchFileCount }) }}
</span>
</div>
<p class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ t('chat.shippingProcessing.batchStatusTitle') }} · {{ statusNotice }}</p>
@@ -632,14 +710,14 @@ async function onPrimaryChatAction() {
<div v-if="handlingSummaryLine" class="mt-1 text-sm text-slate-600 dark:text-slate-300">{{ handlingSummaryLine }}</div>
<div class="mt-4 flex items-end justify-between">
<span class="text-lg font-medium text-blue-600">{{ progressPercent }}% {{ t('chat.shippingProcessing.batchComplete') }}</span>
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ emlAggregate?.sourceSummary.documentCount ?? state.summary.totalDocuments }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
<span class="text-sm text-slate-600 dark:text-slate-300">{{ processedCount }}/{{ batchFileCount }} {{ t('chat.shippingProcessing.batchProcessed') }}</span>
</div>
<div class="mt-3 h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700">
<div class="h-full rounded-full bg-blue-600 transition-all" :style="{ width: `${progressPercent}%` }" />
</div>
</div>
<div v-if="hasConversationStatusGroups" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<div v-if="hasConversationStatusGroups && !compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-status-groups">
<template v-for="group in statusGroupDefs" :key="group.key">
<section v-if="statusGroupTasks(group.key).length" class="overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-slate-700 dark:bg-slate-900">
<button type="button" class="flex w-full items-center justify-between px-3 py-3 text-left" @click="toggleStatusGroup(group.key)">
@@ -652,19 +730,19 @@ async function onPrimaryChatAction() {
<Mail class="mt-0.5 h-4 w-4 text-blue-600" />
<div class="min-w-0 flex-1">
<button type="button" class="flex w-full items-center justify-between gap-2 text-left" @click="toggleEmlTask(task.user_task_no)">
<span class="truncate text-sm font-medium">{{ statusTaskProjection(task)?.sourceSummary?.filename || task.title || task.user_task_no }}</span>
<span class="truncate text-sm font-medium">{{ task.title || task.user_task_no }}</span>
<ChevronDown class="h-4 w-4 shrink-0 transition-transform" :class="expandedEmlTasks.has(task.user_task_no) ? 'rotate-180' : ''" />
</button>
<div class="mt-1 text-xs text-slate-500">{{ t('chat.shippingProcessing.taskFiles', { count: taskFileCount(task) }) }}<span v-if="task.aggregateSummary"> · {{ aggregateStatusLabelFromSummary(task.aggregateSummary) }}</span></div>
<div v-if="task.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(task.blockingReason.code) }}</div>
<div v-if="taskReason(task)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(task)) }}</div>
<div v-if="expandedEmlTasks.has(task.user_task_no)" class="mt-2 space-y-1 border-t border-slate-200 pt-2 dark:border-slate-700" data-testid="shipping-order-extraction-eml-children">
<div v-for="child in taskChildren(task)" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
<div v-for="child in taskChildren(task).filter((item) => !String(item.sourceSummary?.filename || '').toLowerCase().endsWith('.eml'))" :key="child.workItemNo" class="flex items-start justify-between gap-3 rounded-md bg-white px-2 py-1.5 text-xs dark:bg-slate-900">
<div class="min-w-0">
<div class="truncate font-medium">{{ child.sourceSummary.filename || child.workItemNo }}</div>
<div class="text-[11px] text-slate-500">{{ childStageLabel(child) }}</div>
<div v-if="child.blockingReason?.code || child.sourceSummary?.failureReasonCode" class="text-[11px] text-rose-600">{{ userReasonLabel(child.blockingReason?.code || child.sourceSummary?.failureReasonCode) }}</div>
<div v-if="taskReason(child)" class="text-[11px] text-rose-600">{{ displayReason(taskReason(child)) }}</div>
</div>
<span class="shrink-0" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
<span :data-testid="`shipping-order-extraction-child-status-${child.workItemNo}`" class="shrink-0" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ childStatusLabel(child) }}</span>
</div>
</div>
</div>
@@ -674,7 +752,7 @@ async function onPrimaryChatAction() {
</section>
</template>
</div>
<div v-else-if="emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<div v-else-if="!compactProgress && emlAggregate" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30" data-testid="shipping-order-extraction-eml-aggregate">
<article class="overflow-hidden rounded-lg border border-slate-300 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<div class="flex items-start gap-3 border-b border-slate-200 bg-blue-50/50 p-3 dark:border-slate-700 dark:bg-blue-950/20">
<Mail class="mt-0.5 h-5 w-5 text-blue-600" />
@@ -686,7 +764,7 @@ async function onPrimaryChatAction() {
</span>
</div>
<div class="mt-1 text-xs text-slate-600 dark:text-slate-300">{{ aggregateSummaryLabel(emlAggregate) }}</div>
<div v-if="emlAggregate.blockingReason?.code" class="mt-1 text-xs text-rose-600">{{ userReasonLabel(emlAggregate.blockingReason.code) }}</div>
<div v-if="taskReason(emlAggregate)" class="mt-1 text-xs text-rose-600">{{ displayReason(taskReason(emlAggregate)) }}</div>
</div>
</div>
<button type="button" class="flex w-full items-center justify-between px-3 py-2 text-left text-sm" @click="emlAggregateExpanded = !emlAggregateExpanded">
@@ -696,12 +774,12 @@ async function onPrimaryChatAction() {
<div v-if="emlAggregateExpanded" class="space-y-1 border-t border-slate-200 px-3 py-2 dark:border-slate-700">
<div v-for="child in emlAggregateChildren" :key="child.workItemNo" class="flex items-center justify-between gap-3 py-1 text-sm">
<span class="min-w-0 truncate">{{ child.sourceSummary.filename || child.workItemNo }}</span>
<span class="shrink-0 text-xs" :class="child.userStatus === 'failed' || child.userStatus === 'retryable' ? 'text-rose-600' : child.userStatus === 'waiting_human' ? 'text-amber-700' : child.userStatus === 'completed' && child.facts?.uploadState === 'succeeded' ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
<span class="shrink-0 text-xs" :class="isFailedProjection(child) ? 'text-rose-600' : isWaitingProjection(child) ? 'text-amber-700' : isCompletedProjection(child) ? 'text-emerald-600' : 'text-blue-600'">{{ aggregateChildStatusLabel(child) }} · {{ aggregateStageLabel(child) }}</span>
</div>
</div>
</article>
</div>
<div v-else class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
<div v-else-if="!compactProgress" class="flex flex-col gap-2 bg-slate-50 p-2 dark:bg-slate-950/30">
<button type="button" class="flex items-center justify-between rounded-lg border border-slate-200 bg-white px-3 py-3 text-left dark:border-slate-700 dark:bg-slate-900" @click="completedExpanded = !completedExpanded">
<span class="flex items-center gap-3 text-base font-medium"><span class="flex h-7 w-7 items-center justify-center rounded-full bg-blue-100 text-blue-600"><CheckCircle2 class="h-4 w-4" /></span>{{ t('chat.shippingProcessing.candidateFiles', { count: candidateFileCount }) }}</span>
<ChevronDown class="h-5 w-5 transition-transform" :class="completedExpanded ? 'rotate-180' : ''" />
@@ -726,8 +804,16 @@ async function onPrimaryChatAction() {
<div class="flex justify-end border-t border-slate-200 bg-indigo-50/60 p-3 dark:border-slate-700 dark:bg-indigo-950/20">
<div class="flex items-center gap-3">
<button v-if="primaryChatAction" type="button" class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700 disabled:opacity-50" data-testid="shipping-order-extraction-primary-action" :disabled="primaryChatAction.kind === 'retry' && retrying" @click="onPrimaryChatAction">{{ primaryChatAction.kind === 'retry' && retrying ? t('chat.shippingOrderExtractionRetrying') : primaryChatAction.label }}<ArrowRight class="h-4 w-4" /></button>
<button v-if="String(props.runNo || '').trim()" type="button" class="text-sm font-medium text-blue-600 underline-offset-2 hover:underline" data-testid="shipping-order-extraction-view-details" @click="openDetailsDrawer">{{ t('chat.shippingProcessing.viewTaskDetails') }}</button>
<button
v-if="!compactProgress && (hasConversationStatusGroups || String(props.runNo || '').trim())"
type="button"
class="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-blue-700"
data-testid="shipping-order-extraction-open-batch-workbench"
@click="emit('open-batch-workbench')"
>
{{ t('chat.shippingProcessing.openBatchWorkbench') }}
<ArrowRight class="h-4 w-4" />
</button>
</div>
</div>
<div v-if="false" class="flex items-start gap-3">
@@ -841,6 +841,63 @@ describe('ShippingWorkflowTimeline', () => {
});
it('renders localized four-stage labels without duplicating the header summary', async () => {
const processing = processingFromDocuments([buildItem()], {
status_groups: { failed: [], waiting_human: [], processing: [], completed: [] },
four_stage_nodes: [
{ code: 'intake_parse', status: 'passed' },
{ code: 'order_review', status: 'running' },
{ code: 'fulfillment_prep', status: 'pending' },
{ code: 'upload_complete', status: 'pending' },
],
} as Partial<ConversationProcessingProjection>);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller: buildController({ processing }) },
...mountOptions,
});
await flushPromises();
// 断言:批次中心只在总览区呈现统计,标题栏不再重复任务/文件摘要。
expect(wrapper.find('[data-testid="shipping-processing-summary-totals"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-processing-summary-detail"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="shipping-workflow-four-stage-progress"]').text()).toContain('接收解析');
expect(wrapper.text()).not.toContain('chat.shippingNoticeUi.stage.intake_parse');
});
it('opens review directly from a document leaf projection context', async () => {
const processing = processingFromDocuments([buildItem()], {
needs_action: [],
processing: [],
completed: [],
});
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller: buildController({ processing }) },
...mountOptions,
});
await flushPromises();
const card = wrapper.findComponent({ name: 'ShippingConversationProcessingCard' });
await card.vm.$emit('projection-action', {
projection: {
workItemNo: 'DOCUMENT:191',
rootOrderTaskNo: 'INTAKE:SNI-1',
runNo: 'RUN-LEAF',
caseNo: 'SNRC-LEAF',
sourceSummary: { documentId: 191 },
},
item: { actionCode: 'open_order_review', intent: 'open_order_review' },
});
await flushPromises();
// 断言:叶子不能按父任务号回查,必须直接使用后端下发的 Run/Case/文档上下文。
expect(routerPush).toHaveBeenCalledWith(expect.objectContaining({
query: expect.objectContaining({
mode: 'order-review', run_no: 'RUN-LEAF', case_no: 'SNRC-LEAF', document_id: '191', focus_task_no: 'INTAKE:SNI-1',
}),
}));
});
it('expands all effective PDFs for one task even when they belong to different runs', async () => {
@@ -1,10 +1,10 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「本次处理中」面板——OT 任务卡 + 按需展开的文件明细。
* 用途:聊天页右侧「批次进度中心」——OT 任务卡 + 按需展开的文件明细。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* conversationProcessingProjection、DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;面板摘要为双行「N 任务 · M 文件」+
* 「待我处理 / 系统处理中」;截断时展示 has_more 提示;
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
* 文件总览和进度仅消费后端批次 summary;
* mapUserTaskObjectsToFileRows 合成文件行;取消/重识别走 Run API;
* 路由 focus_task_no / 服务端 focused_task_no 驱动本地选中卡;
* 详情抽屉仅用列表投影,不再请求 WorkflowItem 详情 API。
@@ -14,10 +14,12 @@ import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { ChevronDown, ChevronRight, Lock, RefreshCw } from 'lucide-vue-next';
import { downloadWorkspaceShippingExcelFile } from '@/features/chat/shipping/shippingDownload';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import { CHAT_PAGE_KEY } from '@/features/chat/composables/chat.context';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import { useShippingProcessGateRecovery } from '@/features/shipping-process-gates/composables/useShippingProcessGateRecovery';
import {
cancelWorkspaceShippingOrderExtractionRun,
reparseWorkspaceShippingOrderExtractionRun,
@@ -54,6 +56,10 @@ const props = defineProps<{
controller?: UseShippingNoticeWorkflowReturn | null;
}>();
const emit = defineEmits<{
close: [];
}>();
const { t, te } = useI18n();
const msg = useMessage();
const route = useRoute();
@@ -64,6 +70,7 @@ const gateNavigationContext = computed(() => ({
agentId: String(route.params.agentId || ''),
conversationId: String(props.conversationId || route.query.conversation_id || ''),
}));
const { submitPrimaryAction: submitGatePrimaryAction } = useShippingProcessGateRecovery();
/**
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
@@ -115,14 +122,131 @@ const processingWorkItems = computed((): ShippingProcessingProjection[] => (
? ctl.value.processingWorkItems.value
: []
));
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
upload_complete: 'uploadComplete',
};
function batchFourStageLabelKey(code: string): string {
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
}
async function downloadBatchArtifact(taskNo: string) {
if (!taskNo) return;
try {
await downloadWorkspaceShippingExcelFile(taskNo);
} catch (err) {
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.singleDownloadFailed'));
}
}
/** 批量下载仅遍历后端标记为可下载的产物,单项失败不阻断其余产物。 */
async function downloadAllBatchArtifacts() {
const artifacts = batchArtifacts.value.filter((artifact) => artifact.action?.enabled);
if (!artifacts.length) return;
let failed = 0;
for (const artifact of artifacts) {
try {
await downloadWorkspaceShippingExcelFile(artifact.order_task_no);
} catch {
failed += 1;
}
}
if (failed) {
msg.error(t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: failed }));
}
}
const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
/**
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
* 不能直接填入原型的“处理中/需处理”文件统计卡。
*/
function taskFileKeys(task: ConversationProcessingUserTask): string[] {
const keys = new Set<string>();
const collect = (children: ShippingProcessingProjection[]) => {
for (const child of children) {
const nested = child.aggregateChildren || [];
if (nested.length) collect(nested);
const filename = String(child.sourceSummary?.filename || '').trim();
// 聚合父项/邮件容器只提供来源信息,叶子附件才计入业务文件。
if (nested.length || filename.toLowerCase().endsWith('.eml')) continue;
const id = Number(child.sourceSummary?.documentId || 0);
const key = id > 0 ? `document:${id}` : filename ? `filename:${filename}` : '';
if (key) keys.add(key);
}
};
const children = task.aggregateChildren || [];
if (children.length) {
collect(children);
return [...keys];
}
for (const object of task.objects || []) {
if (object.kind !== 'document') continue;
const id = Number(object.document_id || 0);
const filename = String(object.filename || object.label || '').trim();
if (filename.toLowerCase().endsWith('.eml')) continue;
const key = id > 0
? `document:${id}`
: String(object.filename || object.object_key || '').trim();
if (key) keys.add(key);
}
if (keys.size) return [...keys];
// 无 EML 子附件明细时,直接文件可按自身 file_count 回退;EML 不允许伪造附件数。
const taskName = String(task.title || '').trim().toLowerCase();
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
const fallback = Math.max(0, Number(task.file_count || 0));
return Array.from({ length: fallback }, (_, index) => `${task.user_task_no}:file:${index}`);
}
const batchOverview = computed(() => {
const summary = displayProcessing.value?.summary;
// [AUTHORITY] status_groups 表示新版批次投影。其 summary 是后端对完整批次
// 一次裁决的文件事实,即使当前值为 0 也不得从局部展开行重算。
if (displayProcessing.value?.status_groups && summary) {
return {
total: Number(summary.total_files || 0),
processing: Number(summary.processing_files || 0),
completed: Number(summary.completed_files || 0),
needsAction: Number(summary.failed_files || 0) + Number(summary.waiting_human_files || 0),
};
}
const groups = displayProcessing.value?.status_groups;
const failed = groups?.failed || [];
const waiting = groups?.waiting_human || [];
const processingTasks = groups?.processing || displayProcessing.value?.processing || [];
const completed = groups?.completed || displayProcessing.value?.completed || [];
const seen = new Set<string>();
const count = (tasks: ConversationProcessingUserTask[]) => tasks.reduce((total, task) => {
let count = 0;
for (const key of taskFileKeys(task)) {
if (seen.has(key)) continue;
seen.add(key);
count += 1;
}
return total + count;
}, 0);
const needsAction = count([...failed, ...waiting]);
const processingCount = count(processingTasks);
const completedCount = count(completed);
const computedTotal = needsAction + processingCount + completedCount;
const summaryTotal = Number(displayProcessing.value?.summary?.total_files || 0);
return {
// status_groups 的去重文件集合优先;旧 summary.total_files 只在没有可枚举文件时回退。
total: computedTotal > 0 ? computedTotal : summaryTotal,
processing: processingCount,
completed: completedCount,
needsAction,
};
});
const loading = computed(() => ctl.value.loading.value);
/** 初始加载:首次打开投影仍为空时显示摘要占位。 */
const initialLoading = computed(() => Boolean(ctl.value.initialLoading?.value));
/** 用户主动刷新(刷新按钮 / 重试 / 重解析等):驱动顶部刷新图标旋转。 */
const manualRefreshing = computed(() => Boolean(ctl.value.manualRefreshing?.value));
const isRefreshing = computed(() => Boolean(ctl.value.isRefreshing?.value));
const error = computed(() => ctl.value.error.value);
const routeFocusedTaskNo = computed(() => String(
route.query.focus_task_no
@@ -607,6 +731,22 @@ async function onTaskProjectionAction(payload: {
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
return;
}
if (code === 'retry_inventory_preparation') {
const gateSummary = projection.processGate;
if (!gateSummary) {
msg.warning(t('workspace.shippingNotice.processGate.noAction'));
return;
}
// Gate 执行器统一处理 execution_no、乐观锁与幂等键;批次卡不自行组装写请求。
const result = await submitGatePrimaryAction(gateSummary, {
actionCode: code,
navigationContext: gateNavigationContext.value,
});
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
await ctl.value.refresh();
}
return;
}
if (code === 'retry_parse' || item.intent === 'retry') {
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
return;
@@ -615,7 +755,7 @@ async function onTaskProjectionAction(payload: {
void onRefresh();
return;
}
if (item.intent === 'open_order_review') {
if (item.intent === 'open_order_review' || code === 'open_order_review') {
const task = [
...(displayProcessing.value?.needs_action || []),
...(displayProcessing.value?.processing || []),
@@ -623,7 +763,21 @@ async function onTaskProjectionAction(payload: {
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) {
void onProcessingTaskAction({ task, action: code || 'open_review' });
return;
}
// 附件叶子的 workItemNo 为 DOCUMENT:<id>,不会等于 EML 父任务 INTAKE:<no>。
// 此处直接消费叶子投影下发的 Run/Case/Document,禁止从父任务猜测复核上下文。
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: projection.sourceSummary?.documentId,
caseNo: projection.caseNo,
taskNo: projection.rootOrderTaskNo || taskNo,
});
return;
}
if (item.intent === 'view_result' || code === 'focus_task') {
@@ -696,11 +850,20 @@ watch(
<template>
<aside
class="flex w-full shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)] transition-[width] duration-200 md:w-[clamp(20rem,28vw,30rem)]"
class="flex min-w-0 flex-1 shrink-0 flex-col border-l border-default bg-surface shadow-[-16px_0_40px_rgba(15,23,42,0.10)] transition-[width] duration-200"
:class="collapsed ? '!w-14' : ''"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary"
data-testid="shipping-workflow-close"
:title="t('chat.shippingProcessing.closeWorkbench')"
@click="emit('close')"
>
×
</button>
<component
:is="hasPinnedProcessingTasks ? 'div' : 'button'"
:type="hasPinnedProcessingTasks ? undefined : 'button'"
@@ -733,18 +896,6 @@ watch(
{{ t('chat.shippingProcessing.loading') }}
</template>
<template v-else-if="displayProcessing">
<div data-testid="shipping-processing-summary-totals">
{{ t('chat.shippingProcessing.summaryTasksAndFiles', {
tasks: Number(displayProcessing.summary.total_tasks || 0),
files: Number(displayProcessing.summary.total_files || 0),
}) }}
</div>
<div data-testid="shipping-processing-summary-detail">
{{ t('chat.shippingProcessing.summaryLineDetail', {
needsAction: Number(displayProcessing.summary.needs_action || 0),
processing: Number(displayProcessing.summary.processing || 0),
}) }}
</div>
<div
v-if="displayProcessing.summary.has_more_active || displayProcessing.summary.has_more_history"
class="text-[11px] text-muted"
@@ -777,12 +928,84 @@ watch(
>
<RefreshCw
class="h-3.5 w-3.5"
:class="{ 'animate-spin': initialLoading || manualRefreshing }"
:class="{ 'animate-spin': isRefreshing }"
/>
</button>
</div>
<div v-if="!collapsed" class="shrink-0 p-3 pb-0">
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-y-auto p-5">
<div
v-if="displayProcessing"
class="mb-4 grid grid-cols-2 gap-3 xl:grid-cols-4"
data-testid="shipping-workflow-overview"
>
<div class="rounded-xl border border-default bg-surface p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.totalFiles') }}</div><div class="mt-1 text-2xl font-semibold text-primary">{{ batchOverview.total }}</div></div>
<div class="rounded-xl border border-brand-200 bg-brand-50/60 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.processing') }}</div><div class="mt-1 text-2xl font-semibold text-brand-700">{{ batchOverview.processing }}</div></div>
<div class="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.completed') }}</div><div class="mt-1 text-2xl font-semibold text-emerald-700">{{ batchOverview.completed }}</div></div>
<div class="rounded-xl border border-rose-200 bg-rose-50/70 p-4"><div class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.overview.needsAction') }}</div><div class="mt-1 text-2xl font-semibold text-rose-700">{{ batchOverview.needsAction }}</div></div>
</div>
<div
v-if="displayProcessing"
class="mb-4 rounded-xl border border-default bg-surface-muted/60 p-3"
data-testid="shipping-workflow-overview-progress"
>
<div class="mb-2 flex items-center justify-between text-xs font-medium text-secondary">
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.completion', { percent: Math.min(100, Math.round((batchOverview.completed / Math.max(1, batchOverview.total)) * 100)) }) }}</span>
<span>{{ t('chat.shippingProcessing.batchWorkbench.overview.processedOfTotal', { completed: batchOverview.completed, total: batchOverview.total }) }}</span>
</div>
<div class="h-3 overflow-hidden rounded-full bg-surface">
<div
class="h-full rounded-full bg-brand-600 shadow-[0_1px_2px_rgb(37_99_235_/_0.35)] transition-[width]"
:style="{ width: `${Math.min(100, Math.round((batchOverview.completed / Math.max(1, batchOverview.total)) * 100))}%` }"
/>
</div>
</div>
<section v-if="batchFourStageNodes.length" class="mb-4 border-b border-default pb-4" data-testid="shipping-workflow-four-stage-progress">
<div class="grid grid-cols-4 gap-2">
<div v-for="node in batchFourStageNodes" :key="node.code" class="rounded-lg border px-2 py-2 text-center text-xs" :class="node.status === 'passed' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : node.status === 'blocked' ? 'border-amber-300 bg-amber-50 text-amber-800' : node.status === 'running' ? 'border-brand-300 bg-brand-50 text-brand-800' : 'border-default bg-surface-muted text-secondary'">
{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}
</div>
</div>
</section>
<section
class="mb-4 rounded-xl border border-default bg-surface p-4"
data-testid="shipping-workflow-batch-artifacts"
>
<div class="flex items-start justify-between gap-3">
<div>
<h3 class="text-sm font-semibold text-primary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.title') }}</h3>
</div>
<button
type="button"
class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white hover:bg-brand-700 disabled:opacity-50"
:disabled="!batchArtifacts.some((artifact) => artifact.action.enabled)"
data-testid="shipping-workflow-batch-artifact-download"
@click="downloadAllBatchArtifacts"
>
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadAll') }}
</button>
</div>
<div v-if="batchArtifacts.length" class="mt-3 divide-y divide-default">
<div v-for="artifact in batchArtifacts" :key="artifact.order_task_no" class="flex items-center justify-between gap-3 py-2 text-xs">
<span class="truncate text-primary">{{ artifact.filename }}</span>
<div class="flex shrink-0 items-center gap-2">
<span class="text-emerald-700">{{ artifact.status }}</span>
<button
type="button"
class="rounded px-2 py-1 font-medium text-brand-700 hover:bg-brand-50 disabled:opacity-50"
:disabled="!artifact.action.enabled"
:data-testid="`shipping-workflow-batch-artifact-download-${artifact.order_task_no}`"
@click="downloadBatchArtifact(artifact.order_task_no)"
>
{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}
</button>
</div>
</div>
</div>
<p v-else class="mt-3 text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.empty') }}</p>
</section>
<div
v-if="focusTaskBanner"
class="mb-3 rounded-md border border-brand-200 bg-brand-50 px-2.5 py-2 text-[11px] text-brand-900 dark:border-brand-800 dark:bg-brand-950/40 dark:text-brand-100"
@@ -796,6 +1019,7 @@ watch(
:projection="displayProcessing"
:work-items="processingWorkItems"
:conversation-id="conversationId"
:workbench-mode="true"
:has-more-history="Boolean(displayProcessing?.summary?.has_more_history)"
@expand-files="onExpandTaskFiles"
@collapse-files="onCollapseTaskFiles"
@@ -805,7 +1029,7 @@ watch(
/>
<section
v-if="showStandaloneCurrentStage"
v-if="!displayProcessing && showStandaloneCurrentStage"
class="mb-3 rounded-xl border border-brand-200 bg-brand-50/60 p-3 dark:border-brand-900/60 dark:bg-brand-950/20"
data-testid="shipping-workflow-current-stage"
>
@@ -835,6 +1059,7 @@ watch(
<!-- 侧栏内直接展示阻断 Gate 与文件明细,避免重复弹层。 -->
<div
v-if="!displayProcessing"
class="space-y-2"
data-testid="shipping-workflow-compact-gates"
>
@@ -852,7 +1077,7 @@ watch(
<!-- 聚焦任务下的文件行列表:供跨 Run 合并与文件筛选断言。 -->
<ul
v-if="expandedTask && items.length"
v-if="!displayProcessing && expandedTask && items.length"
class="my-3 space-y-1.5"
>
<li