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

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

No files matched your search

@@ -117,6 +117,210 @@ function buildWorkItem(
}
describe('ShippingConversationProcessingCard', () => {
it('only exposes file cancellation when the backend explicitly authorizes cancel_unit', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-UNIT', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-UNIT', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-9', label: 'cancel.pdf', filename: 'cancel.pdf',
document_id: 9, root_document_id: 9, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-UNIT', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-UNIT').sourceSummary, documentId: 9 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [{ code: 'cancel_unit', enabled: true }],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('summary').trigger('click');
await wrapper.find('[data-testid="shipping-processing-file-cancel"]').trigger('click');
expect(wrapper.emitted('fileAction')?.[0]?.[0]).toMatchObject({
action: 'cancel_unit', projection: { workItemNo: 'OT-CANCEL-UNIT' },
});
});
it('does not fall back to legacy cancellation when ui_state revokes it', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-CANCEL-REVOKED', group: 'processing', status_label: 'extracting',
file_count: 1, run_no: 'RUN-CANCEL-REVOKED', can_append: false,
objects: [{ kind: 'document', object_key: 'DOC-10', label: 'revoked.pdf', filename: 'revoked.pdf',
document_id: 10, root_document_id: 10, status_label: 'extracting' }],
}];
const workItem = buildWorkItem('OT-CANCEL-REVOKED', {
availableActions: ['cancel_unit'],
sourceSummary: { ...buildWorkItem('OT-CANCEL-REVOKED').sourceSummary, documentId: 10 },
uiState: {
status: 'running',
stage: 'document_parsing',
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [workItem], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// ui_state 已出现即表示后端完成了正式动作裁决;遗留 availableActions 不得重新授权。
expect(wrapper.find('[data-testid="shipping-processing-file-cancel"]').exists()).toBe(false);
expect(wrapper.emitted('fileAction')).toBeUndefined();
});
it('does not render legacy document_names as a batch file row without a live leaf projection', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-HISTORICAL-SNAPSHOT', group: 'processing', status_label: 'extracting',
title: 'legacy-run.pdf', document_names: ['legacy-run.pdf'], file_count: 1,
run_no: 'RUN-HISTORICAL-SNAPSHOT', can_append: false,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
// 批次中心没有实时叶子投影时不得由历史 Run 快照补造文件行或操作入口。
expect(wrapper.find('[data-testid="shipping-processing-file-OT-HISTORICAL-SNAPSHOT-document-0"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('legacy-run.pdf');
});
it('uses the live leaf summary instead of a stale task object in batch mode', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'OT-LIVE-LEAF', group: 'processing', status_label: 'extracting',
title: 'snapshot-old-name.pdf', file_count: 1, run_no: 'RUN-LIVE-LEAF', can_append: false,
objects: [{
kind: 'document', object_key: 'DOC-88', label: 'snapshot-old-name.pdf',
filename: 'snapshot-old-name.pdf', document_id: 88, root_document_id: 88,
status_label: 'pending_review',
}],
}];
const live = buildWorkItem('OT-LIVE-LEAF', {
runNo: 'RUN-LIVE-LEAF',
sourceSummary: {
emailSubject: null, filename: 'realtime-name.pdf', documentId: 88,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-REALTIME',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [live], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-88"]');
expect(row.text()).toContain('realtime-name.pdf');
expect(row.text()).toContain('PO:PO-REALTIME');
expect(row.text()).not.toContain('snapshot-old-name.pdf');
});
it('expands EML files only from the live aggregate work item', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-LIVE', group: 'processing', status_label: 'extracting',
title: 'snapshot-mail.eml', document_names: ['snapshot-attachment.pdf'],
file_count: 1, run_no: 'RUN-EML-LIVE', can_append: false,
aggregateChildren: [],
}];
const liveChild = buildWorkItem('DOCUMENT:77', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: null, filename: 'live-attachment.pdf', documentId: 77,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-EML-LIVE',
},
uiState: {
status: 'running', stage: 'order_review', lifecycleStage: 'order_review',
lifecycleEntries: [{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' }],
blocking_reason: null, primary_action: null, secondary_actions: [],
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-LIVE', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-LIVE', runNo: 'RUN-EML-LIVE',
sourceSummary: {
emailSubject: 'Live mail', filename: 'live-mail.eml', documentId: null,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: null,
},
aggregateChildren: [liveChild],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.get('[data-testid="shipping-processing-file-DOC-77"]');
expect(row.text()).toContain('live-attachment.pdf');
expect(row.text()).toContain('PO:PO-EML-LIVE');
expect(wrapper.text()).not.toContain('snapshot-attachment.pdf');
});
it('keeps an EML attachment when it has a linked child order task', async () => {
const projection = buildProjection();
projection.processing = [{
user_task_no: 'INTAKE:EML-WITH-CHILD-OT', group: 'processing', status_label: 'extracting',
title: 'mail.eml', file_count: 2, run_no: 'RUN-EML-WITH-CHILD-OT', can_append: false,
}];
const firstAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'first.pdf', documentId: 266,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-FIRST',
},
childOrderTasks: [{
orderTaskNo: 'OT-EML-WITH-CHILD-OT-C1', status: 'blocked', stage: 'inventory_matching',
customerName: null, poNumber: 'PO-SECOND', lastActivityAt: null,
}],
});
const secondAttachment = buildWorkItem('OT-EML-WITH-CHILD-OT-C1', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: null, filename: 'second.pdf', documentId: 267,
documentCount: 1, parsedDocumentCount: 1, candidateCount: 1,
customerName: null, poNumber: 'PO-SECOND',
},
});
const liveEmlRoot = buildWorkItem('INTAKE:EML-WITH-CHILD-OT', {
sourceType: 'eml', rootOrderTaskNo: 'OT-EML-WITH-CHILD-OT',
sourceSummary: {
emailSubject: 'Mail', filename: 'mail.eml', documentId: null,
documentCount: 2, parsedDocumentCount: 2, candidateCount: 2,
customerName: null, poNumber: null,
},
aggregateChildren: [firstAttachment, secondAttachment],
});
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection, workItems: [liveEmlRoot], workbenchMode: true },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-266"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-file-DOC-267"]').exists()).toBe(true);
expect(wrapper.text()).toContain('处理中 · 2 个文件');
});
it('renders needs_action / processing groups and collapsible processing records with three subsections', async () => {
const wrapper = mount(ShippingConversationProcessingCard, {
props: { projection: buildProjection() },
@@ -127,8 +331,9 @@ describe('ShippingConversationProcessingCard', () => {
expect(wrapper.find('[data-testid="shipping-conversation-processing-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-failed"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-processing-group-processing"]').exists()).toBe(true);
expect(wrapper.text()).toContain('异常 / 失败 · 1 个任务');
expect(wrapper.text()).toContain('系统处理中 · 1 个任务');
// 批次中心统一按文件计数;旧任务数文案不再是页面统计口径。
expect(wrapper.text()).toContain('异常 · 0 个文件');
expect(wrapper.text()).toContain('处理中 · 0 个文件');
expect(wrapper.text()).toContain('刚刚创建');
// 处理记录默认折叠;标题 count = completed + history 返回条数。
@@ -559,7 +764,110 @@ describe('ShippingConversationProcessingCard', () => {
});
await flushPromises();
expect(wrapper.text()).toContain('待复核');
// 旧聚合卡不再显示内部 Case 状态;工作台文件行才展示后端 ui_state。
expect(wrapper.text()).not.toContain('review_case_draft');
expect(wrapper.text()).not.toContain('review_case_draft');
});
it('renders a compact V3 file row with named lifecycle entries', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE',
run_no: 'RUN-LIFECYCLE',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE', {
runNo: 'RUN-LIFECYCLE',
caseNo: 'CASE-LIFECYCLE',
sourceSummary: {
emailSubject: null,
filename: 'lifecycle.pdf',
documentId: 9,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-LIFECYCLE',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-9"]');
expect(row.exists()).toBe(true);
expect(row.text()).toContain('lifecycle.pdf');
expect(row.text()).toContain('PO:PO-LIFECYCLE');
expect(row.text()).toContain('通知准备');
expect(row.text()).toContain('订单复核 · 可进入');
expect(row.text()).toContain('通知准备 · 当前可处理');
expect(row.text()).toContain('通知完成 · 前置未完成');
});
it('fails closed when a lifecycle entry has an unknown backend state', async () => {
const projection = buildProjection();
projection.processing = [{
...projection.processing[0],
user_task_no: 'OT-LIFECYCLE-UNKNOWN',
run_no: 'RUN-LIFECYCLE-UNKNOWN',
file_count: 1,
}];
const wrapper = mount(ShippingConversationProcessingCard, {
props: {
projection,
workbenchMode: true,
workItems: [buildWorkItem('OT-LIFECYCLE-UNKNOWN', {
runNo: 'RUN-LIFECYCLE-UNKNOWN',
sourceSummary: {
emailSubject: null,
filename: 'unknown-entry.pdf',
documentId: 10,
documentCount: 1,
parsedDocumentCount: 1,
candidateCount: 1,
customerName: null,
poNumber: 'PO-UNKNOWN',
},
uiState: {
status: 'running',
stage: 'inventory_match',
lifecycleStage: 'fulfillment_prep',
lifecycleEntries: [
{ code: 'order_review', state: 'paused', targetSurface: 'order_lifecycle_workbench' },
] as unknown as ShippingProcessingProjection['uiState']['lifecycleEntries'],
blocking_reason: null,
primary_action: null,
secondary_actions: [],
},
})],
},
global: { plugins: [i18n] },
});
await flushPromises();
const row = wrapper.find('[data-testid="shipping-processing-file-DOC-10"]');
const orderReview = row.findAll('button').find((button) => button.text().includes('订单复核'));
expect(orderReview?.attributes('disabled')).toBeDefined();
await orderReview?.trigger('click');
expect(wrapper.emitted('openLifecycleStage')).toBeUndefined();
});
});
@@ -13,10 +13,11 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight } from 'lucide-vue-next';
import { ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-vue-next';
import type {
ConversationProcessingProjection,
ConversationProcessingUserTask,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
} from '@/features/chat/types/shipping.api.types';
import { getPrimaryDocumentName } from '@/features/chat/shipping/conversationProcessingDisplay';
@@ -30,8 +31,9 @@ import {
} from '@/features/chat/shipping/conversationProcessingState';
import {
resolveShippingProcessingMessage,
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
resolveShippingProcessingStatusLabel,
shippingProcessingStageKey,
} from '@/features/chat/shipping/shippingProcessingLabels';
import { flattenBusinessFileProjections } from '@/features/chat/shipping/conversationProcessingProjection';
import { resolveConversationTaskActionPresentation, resolveProcessingActionPresentation } from '@/features/shipping-progress/actionPresentation';
@@ -48,6 +50,13 @@ const props = defineProps<{
hasMoreHistory?: boolean;
/** 批次中心按状态 → EML → 文件展示,不再嵌入任务级 15 节点进度。 */
workbenchMode?: boolean;
/** 批次四阶段筛选;保留状态/EML 分组,仅隐藏不属于当前阶段的任务。 */
lifecycleFilter?: 'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete';
/** 批次中心本地搜索:只筛叶子文件,父 EML 卡仍保留。 */
fileSearchQuery?: string;
/** 后端已授权下载的正式 Excel 对应 OT。 */
downloadableTaskNos?: string[];
selectedDownloadTaskNos?: string[];
}>();
const emit = defineEmits<{
@@ -61,6 +70,12 @@ const emit = defineEmits<{
intakeAction: [payload: { item: ShippingProcessingProjection; action: string }];
/** OT 卡内统一进度动作。 */
projectionAction: [payload: { projection: ShippingProcessingProjection; item: ActionPresentationItem }];
downloadArtifact: [taskNo: string];
toggleDownloadSelection: [taskNo: string];
/** 文件级生命周期入口;父级只切换工作台展示,不在导航时写入业务状态。 */
openLifecycleStage: [payload: { projection: ShippingProcessingProjection; entry: ShippingProcessingLifecycleEntry }];
/** 单文件低频操作;仅当后端明确授权该动作时才发出。 */
fileAction: [payload: { projection: ShippingProcessingProjection; action: string }];
}>();
const { t, te } = useI18n();
@@ -76,8 +91,17 @@ type WorkbenchFileRow = {
filename?: string | null;
document_id?: number | null;
status_label?: string | null;
po_number?: string | null;
projection?: ShippingProcessingProjection;
};
const LIFECYCLE_STAGE_CODES = ['order_review', 'fulfillment_prep', 'upload_complete'] as const;
type LifecycleStageCode = typeof LIFECYCLE_STAGE_CODES[number];
const LIFECYCLE_STAGE_LABEL_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
order_review: 'orderReview',
fulfillment_prep: 'fulfillmentPrep',
upload_complete: 'uploadComplete',
};
/** 唯一进度源:统一 conversation_processing / work_items 合成投影。 */
const activeProjection = computed((): ConversationProcessingProjection | null => (
@@ -100,6 +124,23 @@ const waitingHumanTasks = computed(() => statusGroups.value?.waiting_human
|| (activeProjection.value?.needs_action || []).filter((task) => task.userGroup === 'waiting_human'));
const processingTasks = computed(() => statusGroups.value?.processing || activeProjection.value?.processing || []);
/** 任务只要含一个命中附件即保留,避免筛选后打散同一封 EML 的上下文。 */
function taskMatchesLifecycleFilter(task: ConversationProcessingUserTask): boolean {
const filter = props.lifecycleFilter || 'all';
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
// 非批次中心保留历史任务卡兼容展示;只有批次中心才按叶子文件筛选。
if (!props.workbenchMode && filter === 'all' && !query) return true;
return workbenchFileRows(task).some((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
return !query || [file.filename, file.label, file.po_number]
.some((value) => String(value || '').toLowerCase().includes(query));
});
}
const visibleFailedTasks = computed(() => failedTasks.value.filter(taskMatchesLifecycleFilter));
const visibleWaitingHumanTasks = computed(() => waitingHumanTasks.value.filter(taskMatchesLifecycleFilter));
const visibleProcessingTasks = computed(() => processingTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCompletedTasks = computed(() => completedTasks.value.filter(taskMatchesLifecycleFilter));
/** history 中非取消 →「历史版本」。 */
const historyVersionTasks = computed(() => historyTasks.value.filter(
(task) => String(task.status_label || '').trim().toLowerCase() !== 'cancelled',
@@ -109,6 +150,8 @@ const historyVersionTasks = computed(() => historyTasks.value.filter(
const cancelledHistoryTasks = computed(() => historyTasks.value.filter(
(task) => String(task.status_label || '').trim().toLowerCase() === 'cancelled',
));
const visibleHistoryVersionTasks = computed(() => historyVersionTasks.value.filter(taskMatchesLifecycleFilter));
const visibleCancelledHistoryTasks = computed(() => cancelledHistoryTasks.value.filter(taskMatchesLifecycleFilter));
/** 处理记录标题计数:当前返回的 completed + history。 */
const recordTaskCount = computed(() => (
@@ -249,6 +292,45 @@ function groupTitle(task: ConversationProcessingUserTask): string {
/** 工作台文件行:只展示后端 document objects,避免用任务标题冒充文件。 */
function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const children = task.aggregateChildren || [];
// [AUTHORITY] 批次模式只以实时 work_items 作为文件行真相。Conversation task 的
// children / objects / document_names 是 Run 级兼容快照,可用于非批次卡历史展示,
// 但不得重建批次中的文件名、状态、阶段或操作。
if (props.workbenchMode) {
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).flatMap((item) => {
const isTaskRoot = String(item.rootOrderTaskNo || '').trim() === taskNo
|| String(item.workItemNo || '').trim() === taskNo;
if (!isTaskRoot) return [];
// EML 父项的实时附件只存在于 aggregateChildren;展开同一份后端 work_item,
// 不读取 conversation task 兼容快照。
return item.sourceType === 'eml'
? flattenBusinessFileProjections([item])
: [item];
}).filter((item) => (
Number(item.sourceSummary?.documentId || 0) > 0
));
const seenLiveDocumentIds = new Set<number>();
const uniqueLiveLeaves = liveLeaves.filter((item) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
if (seenLiveDocumentIds.has(documentId)) return false;
seenLiveDocumentIds.add(documentId);
return true;
});
return uniqueLiveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
if (children.length) {
return flattenBusinessFileProjections(children).map((child, index) => {
const filename = String(child.sourceSummary?.filename || '').trim();
@@ -259,6 +341,7 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
label: filename || child.workItemNo || `文件 ${index + 1}`,
filename: filename || child.workItemNo || `文件 ${index + 1}`,
status_label: String(child.uiState?.status || child.userStatus || child.status || ''),
po_number: child.sourceSummary?.poNumber || null,
projection: child,
};
});
@@ -278,6 +361,7 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
filename: item.filename,
document_id: item.document_id,
status_label: item.status_label,
po_number: directFileProjection?.sourceSummary?.poNumber || null,
projection: directFileProjection?.sourceType === 'direct_pdf'
? directFileProjection
: undefined,
@@ -285,15 +369,60 @@ function workbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileR
}
const taskName = String(task.title || '').trim().toLowerCase();
if (taskName.endsWith('.eml') || task.aggregateSummary?.intakeNo) return [];
// 新版实时投影可只返回 work_items,不重复旧 task.objects;此时以同一 OT 的叶子
// document 投影生成行,确保文件状态、阶段和按钮仍完全来自后端。
const taskNo = String(task.user_task_no || '').trim();
const liveLeaves = (props.workItems || []).filter((item) => (
String(item.rootOrderTaskNo || '').trim() === taskNo
&& Number(item.sourceSummary?.documentId || 0) > 0
&& !item.childOrderTasks?.length
));
if (liveLeaves.length) {
return liveLeaves.map((item, index) => {
const documentId = Number(item.sourceSummary?.documentId || 0);
const filename = String(item.sourceSummary?.filename || '').trim();
return {
kind: 'document' as const,
object_key: documentId ? `DOC-${documentId}` : `${taskNo}-live-${item.workItemNo || index}`,
label: filename || item.workItemNo || `文件 ${index + 1}`,
filename: filename || item.workItemNo || `文件 ${index + 1}`,
document_id: documentId || null,
status_label: String(item.uiState?.status || item.userStatus || item.status || ''),
po_number: item.sourceSummary?.poNumber || null,
projection: item,
};
});
}
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,
po_number: null,
}));
}
/** 阶段筛选只收窄附件行,EML 卡本身仍保留以便用户识别邮件来源。 */
function visibleWorkbenchFileRows(task: ConversationProcessingUserTask): WorkbenchFileRow[] {
const filter = props.lifecycleFilter || 'all';
const rows = workbenchFileRows(task);
const query = String(props.fileSearchQuery || '').trim().toLowerCase();
return rows.filter((file) => {
if (filter !== 'all' && String(file.projection?.uiState?.lifecycleStage || '') !== filter) return false;
if (!query) return true;
return [file.filename, file.label, file.po_number].some((value) => String(value || '').toLowerCase().includes(query));
});
}
function fileDownloadTaskNo(file: WorkbenchFileRow): string | null {
const taskNo = String(file.projection?.rootOrderTaskNo || '').trim();
return taskNo && (props.downloadableTaskNos || []).includes(taskNo) ? taskNo : null;
}
function isDownloadSelected(taskNo: string): boolean {
return (props.selectedDownloadTaskNos || []).includes(taskNo);
}
/** 状态组标题按文件计数,与批次总览保持同一口径。 */
function groupFileCount(tasks: ConversationProcessingUserTask[]): number {
const seen = new Set<string>();
@@ -320,20 +449,51 @@ function workbenchFileReason(file: WorkbenchFileRow, task: ConversationProcessin
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 resolveShippingProcessingReasonLabel(reason, te, t);
}
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 || '');
/** 文件工作面显示四阶段业务语义;技术 stage 仍保留给进度诊断,不用于入口可达性。 */
function workbenchFileLifecycleStage(file: WorkbenchFileRow): string {
const code = String(file.projection?.uiState?.lifecycleStage || '').trim();
const key = LIFECYCLE_STAGE_LABEL_KEYS[code];
return key
? t(`chat.shippingNoticeUi.stage.${key}`)
: t('chat.shippingProcessing.stageLabel.waiting_system_start');
}
/** 生命周期入口仅消费后端投影;禁止按候选、Case 或阶段顺序二次裁决。 */
function lifecycleEntries(file: WorkbenchFileRow): ShippingProcessingLifecycleEntry[] {
return file.projection?.uiState?.lifecycleEntries || [];
}
function lifecycleEntry(file: WorkbenchFileRow, target: LifecycleStageCode): ShippingProcessingLifecycleEntry | null {
return lifecycleEntries(file).find((entry) => entry.code === target) || null;
}
function lifecycleEntryState(file: WorkbenchFileRow, target: LifecycleStageCode): 'available' | 'current' | 'unavailable' {
const state = lifecycleEntry(file, target)?.state;
// [FAIL-CLOSED] 服务端新增或异常状态不得被 UI 当作可进入工作台。
return state === 'available' || state === 'current' ? state : 'unavailable';
}
function lifecycleEntryLabel(file: WorkbenchFileRow, target: LifecycleStageCode): string {
const stage = t(`chat.shippingNoticeUi.stage.${LIFECYCLE_STAGE_LABEL_KEYS[target]}`);
const state = lifecycleEntryState(file, target);
const stateKey = state === 'current'
? 'chat.shippingOrderReview.lifecycle.current'
: state === 'available'
? 'chat.shippingOrderReview.lifecycle.available'
: 'chat.shippingOrderReview.lifecycle.blocked';
return `${stage} · ${t(stateKey)}`;
}
function onOpenLifecycleStage(file: WorkbenchFileRow, lifecycleStage: LifecycleStageCode) {
const entry = lifecycleEntry(file, lifecycleStage);
if (!file.projection || !entry) return;
if (lifecycleEntryState(file, lifecycleStage) === 'unavailable') return;
emit('openLifecycleStage', { projection: file.projection, entry });
}
/** 叶子文件动作由自身 ui_state 裁决;没有叶子投影时不伪造可操作按钮。 */
@@ -392,11 +552,7 @@ function taskReasonLabel(task: ConversationProcessingUserTask): string {
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();
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 同一 EML 聚合卡状态计数;仅用后端下发的 aggregateSummary,不从 UI 状态推导。 */
@@ -548,7 +704,27 @@ function presentationActionLabel(task: ConversationProcessingUserTask, item: Act
if (key && te(key)) return t(key);
const extractionKey = `chat.shippingOrderExtractionAction.${code}`;
if (te(extractionKey)) return t(extractionKey);
return code;
return t('chat.shippingProcessing.action.unknown');
}
/**
* 文件低频操作优先读取正式 ui_state;旧 availableActions 仅兼容未下发 ui_state 的旧投影。
* 一旦后端提供 ui_state,遗留字段绝不能重新授予已撤销的操作。
*/
function canCancelFile(file: WorkbenchFileRow): boolean {
const projection = file.projection;
if (!projection) return false;
if (projection.uiState) {
return projection.uiState.secondary_actions.some(
(action) => action.enabled && action.code === 'cancel_unit',
);
}
return projection.availableActions.includes('cancel_unit');
}
function onFileAction(file: WorkbenchFileRow, action: string) {
if (!file.projection || action !== 'cancel_unit' || !canCancelFile(file)) return;
emit('fileAction', { projection: file.projection, action });
}
/**
@@ -579,8 +755,7 @@ function toggleHistorySection() {
* Intake 阶段文案。
*/
function intakeStageLabel(item: ShippingProcessingProjection): string {
const key = shippingProcessingStageKey(item.stage);
return te(key) ? t(key) : String(item.stage || '');
return resolveShippingProcessingStageLabel(item.stage, te, t);
}
</script>
@@ -591,15 +766,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-conversation-processing-card"
>
<section
v-if="failedTasks.length"
v-if="visibleFailedTasks.length"
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.batchWorkbench.groups.failed', { count: groupFileCount(failedTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.failed', { count: groupFileCount(visibleFailedTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in failedTasks"
v-for="task in visibleFailedTasks"
:key="task.user_task_no"
class="rounded-lg border px-2.5 py-2 transition"
:class="[
@@ -649,13 +824,24 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
</button>
<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 v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1">
<span class="w-fit shrink-0 rounded-full bg-rose-100 px-2 py-0.5 font-medium text-rose-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.failedFallback') }}</span>
<button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-rose-300 px-2 py-0.5 font-medium text-rose-700 hover:bg-rose-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button>
<label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label>
<button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button>
</div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5">
<div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div>
<div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div>
<details v-if="canCancelFile(file)" class="relative shrink-0">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary>
<button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button>
</details>
</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
@@ -666,7 +852,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
@action="(item) => emit('projectionAction', { projection: projectionForTask(task)!, item })"
/>
<div
v-if="shouldShowTaskLevelActions(task) || (!projectionForTask(task) && canExpandFileDetails(task))"
v-if="shouldShowTaskLevelActions(task) || (!workbenchMode && !projectionForTask(task) && canExpandFileDetails(task))"
class="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1"
data-testid="shipping-processing-task-actions"
>
@@ -686,15 +872,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</section>
<section
v-if="waitingHumanTasks.length"
v-if="visibleWaitingHumanTasks.length"
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.batchWorkbench.groups.waitingHuman', { count: groupFileCount(waitingHumanTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.waitingHuman', { count: groupFileCount(visibleWaitingHumanTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in waitingHumanTasks"
v-for="task in visibleWaitingHumanTasks"
:key="task.user_task_no"
class="rounded-lg border border-amber-400 bg-amber-50/80 px-2.5 py-2 transition dark:border-amber-700 dark:bg-amber-950/30"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -709,13 +895,12 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<div v-if="aggregateStatusLabel(task)" class="mt-1 text-[11px] text-secondary">{{ aggregateStatusLabel(task) }}</div>
</button>
<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 v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-white/70 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center dark:bg-slate-950/30" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div>
<div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-amber-100 px-2 py-0.5 font-medium text-amber-800">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.waitingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md bg-brand-600 px-2 py-0.5 font-medium text-white hover:bg-brand-700" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600 dark:text-rose-300" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</div>
</div>
<SidebarProgressInline
@@ -738,15 +923,15 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</section>
<section
v-if="processingTasks.length"
v-if="visibleProcessingTasks.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">
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(processingTasks) }) }}
{{ t('chat.shippingProcessing.batchWorkbench.groups.processing', { count: groupFileCount(visibleProcessingTasks) }) }}
</div>
<div class="space-y-2">
<article
v-for="task in processingTasks"
v-for="task in visibleProcessingTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2"
:class="focusedTaskNo === task.user_task_no
@@ -790,10 +975,11 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</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 v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-surface-muted/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-sky-100 px-2 py-0.5 font-medium text-sky-700">{{ workbenchFileStatus(file, task) || t('chat.shippingProcessing.batchWorkbench.groups.processingFallback') }}</span><button v-if="filePrimaryActionItem(file)" type="button" class="rounded-md border border-brand-300 px-2 py-0.5 font-medium text-brand-700 hover:bg-brand-50" @click="onFileProjectionAction(file)">{{ presentationActionLabel(task, filePrimaryActionItem(file)!) }}</button><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div><details v-if="canCancelFile(file)" class="relative shrink-0"><summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface-muted" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" /></summary><button type="button" class="absolute right-0 top-7 z-10 whitespace-nowrap rounded border border-rose-200 bg-surface px-2 py-1 text-[11px] text-rose-700 shadow-sm hover:bg-rose-50" data-testid="shipping-processing-file-cancel" @click="onFileAction(file, 'cancel_unit')">{{ t('chat.shippingProcessing.actions.cancelFile') }}</button></details></div>
</div>
</div>
<SidebarProgressInline
@@ -818,7 +1004,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
{{ presentationActionLabel(task, primaryActionItem(task)!) }}
</button>
<button
v-if="canExpandFileDetails(task)"
v-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -841,7 +1027,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</button>
</div>
<button
v-else-if="canExpandFileDetails(task)"
v-else-if="!workbenchMode && canExpandFileDetails(task)"
type="button"
class="mt-1.5 inline-flex items-center gap-1 text-[11px] text-secondary underline-offset-2 hover:text-primary hover:underline"
data-testid="shipping-processing-expand-files"
@@ -902,7 +1088,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
data-testid="shipping-processing-history-body"
>
<div
v-if="completedTasks.length"
v-if="visibleCompletedTasks.length"
data-testid="shipping-processing-history-completed"
>
<div class="mb-1 text-[11px] font-medium text-emerald-700 dark:text-emerald-300">
@@ -910,7 +1096,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in completedTasks"
v-for="task in visibleCompletedTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -934,6 +1120,14 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
<div v-if="taskReasonLabel(task)" class="mt-1 text-[11px] text-rose-600 dark:text-rose-300">
{{ taskReasonLabel(task) }}
</div>
<div v-if="workbenchMode" class="mt-3 space-y-2 border-t border-emerald-200/70 pt-2">
<div v-for="file in visibleWorkbenchFileRows(task)" :key="file.object_key" class="grid gap-x-3 gap-y-1 rounded-md bg-emerald-50/40 px-2 py-1.5 text-[11px] sm:grid-cols-[minmax(10rem,1fr)_auto_auto] sm:items-center" :data-testid="`shipping-processing-file-${file.object_key}`">
<div class="min-w-0"><span class="truncate font-medium text-primary">{{ file.filename || file.label }}</span><span class="ml-1 text-secondary">· {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.po', { value: file.po_number || '-' }) }}</span></div><div class="flex min-w-0 flex-wrap items-center gap-1"><span class="w-fit shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 font-medium text-emerald-700">{{ workbenchFileStatus(file, task) }}</span><label v-if="fileDownloadTaskNo(file)" class="inline-flex items-center gap-1 text-secondary"><input type="checkbox" :checked="isDownloadSelected(fileDownloadTaskNo(file)!)" @change="emit('toggleDownloadSelection', fileDownloadTaskNo(file)!)"><span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.select') }}</span></label><button v-if="fileDownloadTaskNo(file)" type="button" class="rounded-md border border-emerald-300 px-2 py-0.5 font-medium text-emerald-700 hover:bg-emerald-50" @click="emit('downloadArtifact', fileDownloadTaskNo(file)!)">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.download') }}</button></div>
<div class="col-span-full flex min-h-7 items-center justify-between gap-3 border-t border-default pt-1.5"><div class="min-w-0 truncate text-secondary"><span>{{ t('chat.shippingProcessing.batchWorkbench.fileEntries.stage', { value: workbenchFileLifecycleStage(file) }) }}</span><span v-if="workbenchFileReason(file, task)" class="text-rose-600" :title="workbenchFileReason(file, task)"> · {{ t('chat.shippingProcessing.batchWorkbench.fileEntries.blocker', { value: workbenchFileReason(file, task) }) }}</span></div><div v-if="lifecycleEntries(file).length" class="flex shrink-0 flex-wrap justify-end gap-1">
<button v-for="stage in LIFECYCLE_STAGE_CODES" :key="stage" type="button" class="rounded border px-1.5 py-1 text-[11px] font-medium disabled:cursor-not-allowed" :class="lifecycleEntryState(file, stage) === 'current' ? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700' : lifecycleEntryState(file, stage) === 'available' ? 'border-emerald-300 bg-emerald-50 text-emerald-800 hover:bg-emerald-100' : 'border-default bg-surface-muted text-muted'" :disabled="lifecycleEntryState(file, stage) === 'unavailable'" :title="lifecycleEntryState(file, stage) === 'unavailable' ? t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable') : undefined" @click="onOpenLifecycleStage(file, stage)">{{ lifecycleEntryLabel(file, stage) }}</button>
</div></div>
</div>
</div>
<button
v-if="recordViewDetailsItem(task)"
type="button"
@@ -948,7 +1142,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div
v-if="historyVersionTasks.length"
v-if="visibleHistoryVersionTasks.length"
data-testid="shipping-processing-history-versions"
>
<div class="mb-1 text-[11px] font-medium text-slate-600 dark:text-slate-300">
@@ -956,7 +1150,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in historyVersionTasks"
v-for="task in visibleHistoryVersionTasks"
:key="task.user_task_no"
class="rounded-lg border border-default bg-surface/80 px-2.5 py-2"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -990,7 +1184,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div
v-if="cancelledHistoryTasks.length"
v-if="visibleCancelledHistoryTasks.length"
data-testid="shipping-processing-history-cancelled"
>
<div class="mb-1 text-[11px] font-medium text-slate-500 dark:text-slate-400">
@@ -998,7 +1192,7 @@ function intakeStageLabel(item: ShippingProcessingProjection): string {
</div>
<div class="space-y-2">
<article
v-for="task in cancelledHistoryTasks"
v-for="task in visibleCancelledHistoryTasks"
:key="task.user_task_no"
class="rounded-lg border border-dashed border-default bg-surface/60 px-2.5 py-2 opacity-90"
:data-testid="`shipping-processing-task-${task.user_task_no}`"
@@ -77,6 +77,44 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.get('[data-testid="shipping-order-extraction-open-batch-workbench"]').exists()).toBe(true);
});
it('does not present historical handling items or CTA as current work when the live projection exists', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: {
state: buildState({
status: 'review_required',
availableActions: ['review_candidate'],
primaryNotice: 'candidate_confirmation',
handlingItems: [{
category: 'candidate_confirmation', count: 2, reasonCodes: [],
affectedRefs: [], primaryAction: 'review_candidate',
}],
}),
},
global: {
plugins: [i18n],
provide: {
[SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'running' },
summary: { total_files: 1, completed_files: 0, waiting_human_files: 0, failed_files: 0 },
status_groups: {
failed: [], waiting_human: [], processing: [{
user_task_no: 'OT-LIVE', title: 'live.pdf', file_count: 1,
userGroup: 'processing', group: 'processing', aggregateChildren: [],
}], completed: [], cancelled: [], archived: [],
},
}),
processingWorkItems: ref([]),
},
},
},
});
expect(wrapper.text()).not.toContain('候选待人工确认');
expect(wrapper.find('[data-testid="shipping-order-extraction-handling-summary"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('collapses file-level progress when the batch workbench is open', () => {
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState(), runNo: 'SNER-COMPACT', compactProgress: true },
@@ -206,7 +244,7 @@ describe('ShippingOrderExtractionCard', () => {
await wrapper.get('[data-testid="shipping-order-extraction-eml-failed-INTAKE:SNI-DETAIL"] button').trigger('click');
expect(wrapper.get('[data-testid="shipping-order-extraction-eml-children"]').text()).toContain('failed.pdf');
expect(wrapper.text()).toContain('异常 1');
expect(wrapper.text()).toContain('文件处理需要人工确认');
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');
@@ -253,6 +291,8 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('共 2 个文件');
// 关键断言:待人工处理不是完成,聊天摘要必须与批次中心 completed_files 同口径。
expect(wrapper.text()).toContain('0/2 已处理');
expect(wrapper.text()).not.toContain('共 6 个文件');
expect(wrapper.text()).not.toContain('stale.pdf');
});
@@ -454,7 +494,7 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).toContain('3 个文件');
expect(wrapper.text()).toContain('系统处理中');
expect(wrapper.text()).toContain('处理时间偏长');
expect(wrapper.text()).toContain('查看详情');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('刷新状态');
expect(wrapper.text()).not.toContain('取消本次识别');
expect(wrapper.text()).not.toContain('PO-450003.pdf');
@@ -527,7 +567,7 @@ describe('ShippingOrderExtractionCard', () => {
});
expect(wrapper.text()).toContain('订单候选已生成');
expect(wrapper.text()).toContain('候选待人工确认 · 2 项');
expect(wrapper.text()).toContain('继续处理');
expect(wrapper.text()).toContain('打开批次进度中心');
expect(wrapper.text()).not.toContain('部分附件需人工处理');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
});
@@ -586,8 +626,8 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).not.toContain('ST-88');
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-item"]').length).toBe(0);
expect(wrapper.findAll('[data-testid="shipping-order-extraction-handling-primary-action"]').length).toBe(0);
// 失败优先:唯一主 CTA 为重试解析。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').text()).toContain('重试解析');
// 当前原型将执行入口统一收敛到批次进度中心,旧消息卡不再保留重试 CTA。
expect(wrapper.find('[data-testid="shipping-order-extraction-primary-action"]').exists()).toBe(false);
});
it('keeps only the batch workbench CTA for review-required without retry', () => {
@@ -20,7 +20,10 @@ import type {
} from '../../types/shipping.api.types';
import type { ShippingProcessingProjection } from '../../types/shipping.api.types';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
import { shippingProcessingStageKey } from '../../shipping/shippingProcessingLabels';
import {
resolveShippingProcessingReasonLabel,
resolveShippingProcessingStageLabel,
} from '../../shipping/shippingProcessingLabels';
import {
listWorkspaceShippingOrderExtractionDocuments,
listWorkspaceShippingOrderExtractionProgressEvents,
@@ -99,65 +102,9 @@ function taskChildren(task: { aggregateChildren?: ShippingProcessingProjection[]
const projection = statusTaskProjection(task);
if (!projection) return [];
if (projection?.aggregateChildren?.length) return projection.aggregateChildren;
const projectionChildren = (projection?.childOrderTasks || []).map((child) => ({
...projection,
workItemNo: child.orderTaskNo,
status: child.status,
stage: child.stage,
userStatus: child.status === 'completed' ? 'completed' : child.status === 'failed' ? 'failed' : 'running',
userStage: child.stage,
sourceSummary: {
...projection.sourceSummary,
filename: child.orderTaskNo,
documentCount: 1,
},
} as ShippingProcessingProjection));
if (projectionChildren.length) return projectionChildren;
// 系统处理中 work_item 可能只有 EML 摘要;附件真实状态仍由当前 Run 文档列表承载。
const emailName = String(projection.sourceSummary?.filename || task.aggregateSummary?.intakeNo || '').trim().toLowerCase();
const emailRow = emailRows.value.find((row) => (
String(row.fileName || '').trim().toLowerCase() === emailName
|| String(row.intakeId || '').trim() === String(task.aggregateSummary?.intakeNo || '').trim()
));
if (!emailRow) return [];
return childRows(emailRow).map((row) => ({
workItemType: 'order_task',
workItemNo: `DOCUMENT:${row.documentId || row.unitId}`,
sourceType: 'eml',
rootOrderTaskNo: null,
shippingNoticeNo: null,
runNo: props.runNo || props.state.runNo || null,
caseNo: null,
conversationId: null,
submissionNo: '',
intakeNo: String(emailRow.intakeId || task.aggregateSummary?.intakeNo || ''),
status: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_review' : row.status === 'candidate_ready' ? 'completed' : 'processing',
stage: String(row.userVisibleStage || row.status || 'processing'),
progressVersion: 0,
lastActivityAt: '',
currentGate: null,
availableActions: [],
sourceSummary: {
emailSubject: null,
filename: row.fileName,
documentId: row.documentId || null,
documentCount: 1,
parsedDocumentCount: row.status === 'failed' ? 0 : 1,
candidateCount: row.status === 'candidate_ready' ? 1 : 0,
customerName: null,
poNumber: null,
failureReasonCode: row.reasonCode || null,
},
childOrderTasks: [],
userStatus: row.status === 'failed' ? 'failed' : row.status === 'review_required' ? 'waiting_human' : row.status === 'candidate_ready' ? 'completed' : 'running',
userStage: row.userVisibleStage || row.status,
blockingReason: row.explainability?.message ? { code: row.reasonCode || 'DOCUMENT_PROCESSING_FAILED', details: { message: row.explainability.message } } : null,
retryable: false,
primaryAction: null,
facts: { uploadState: row.status === 'candidate_ready' ? 'succeeded' : 'not_created' },
userGroup: null,
} as ShippingProcessingProjection));
// 后端未返回 aggregate_children 时只展示聚合摘要。禁止用 childOrderTasks 或
// 历史聊天 Run 快照重新推导附件、Candidate、阶段或按钮。
return [];
}
function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[]; file_count?: number | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
// EML 是来源容器;统一只计其附件,避免聊天卡与批次中心相差一份 EML 本体。
@@ -183,10 +130,7 @@ function childStatusLabel(child: ShippingProcessingProjection) {
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();
return resolveShippingProcessingReasonLabel(reason, te, t);
}
/** 新投影有 ui_state 时严格消费其状态;旧响应才回退 userStatus / status。 */
function displayProjectionStatus(item: ShippingProcessingProjection): string {
@@ -209,8 +153,7 @@ function taskReason(task: { uiState?: { blocking_reason: import('../../types/shi
}
function childStageLabel(child: ShippingProcessingProjection) {
const stage = String(child.uiState?.stage || child.userStage || child.stage || '').trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
return resolveShippingProcessingStageLabel(stage, te, t);
}
function statusTaskProjection(task: { user_task_no?: string | null; aggregateSummary?: { intakeNo?: string | null } | null }) {
const items = shippingWorkflow?.processingWorkItems.value || [];
@@ -272,8 +215,7 @@ const emlAggregateChildren = computed(() => emlAggregate.value?.aggregateChildre
const emlAggregateExpanded = ref(false);
function aggregateStageLabel(item: ShippingProcessingProjection): string {
const stage = String(item.uiState ? item.uiState.stage : (item.userStage || item.stage || '')).trim();
const key = shippingProcessingStageKey(stage);
return te(key) ? t(key) : stage;
return resolveShippingProcessingStageLabel(stage, te, t);
}
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = displayProjectionStatus(item);
@@ -303,7 +245,14 @@ const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
const displaySummary = computed(() => props.state.summary);
const handlingItems = computed(() => props.state.handlingItems || []);
/**
* 旧聊天消息中的 handlingItems 是当时的 Run 快照;实时会话投影已返回时,
* 绝不能把它重新展示成当前待办或用它决定 CTA。当前待办仅由后端 work_items
* 与其 ui_state 裁决,旧卡在此模式下只保留历史消息本身。
*/
const handlingItems = computed(() => (
hasConversationStatusGroups.value ? [] : (props.state.handlingItems || [])
));
const fileRows = computed(() => props.state.documents || []);
const isEmailRow = (row: ShippingOrderExtractionFileState) => (
row.documentType === 'email_body' || row.fileName?.toLowerCase().endsWith('.eml')
@@ -356,9 +305,10 @@ const failedRows = computed(() => fileRows.value.filter((row) => (
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));
// [AUTHORITY] “已处理/完成率”只表示已经完成通知生命周期的业务文件。
// waiting_human / failed 只是后端裁决出的待处理事项,不能借用历史 Run 的
// “处理过”口径累计为完成,否则会与批次进度中心的 completed_files 冲突。
return Math.max(0, Number(summary?.completed_files || 0));
}
return emlAggregate.value?.aggregateSummary?.completed
?? (props.state.summary.completedDocuments + props.state.summary.reviewRequiredDocuments);
@@ -372,7 +322,7 @@ 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(conversationProcessing.value?.summary?.total_files || 0));
}
return Math.max(0, Number(emlAggregate.value?.sourceSummary.documentCount ?? props.state.summary.totalDocuments));
});
@@ -513,7 +463,7 @@ const handlingSummaryLine = computed(() => {
* 唯一主 CTA:失败→重试解析;需处理→继续处理;否则不展示。
*/
const primaryChatAction = computed((): { kind: 'retry' | 'continue'; label: string } | null => {
if (props.readonly) return null;
if (props.readonly || hasConversationStatusGroups.value) return null;
const actions = props.state.availableActions || [];
const canRetry = actions.includes('retry_failed_attachments')
|| actions.includes('retry_failed_documents')
@@ -735,7 +685,7 @@ async function onPrimaryChatAction() {
</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="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-if="expandedEmlTasks.has(task.user_task_no) && taskChildren(task).length" 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).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>
@@ -30,6 +30,7 @@ function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowI
current_run_no: 'SNER-9',
lifecycle_status: 'extracting',
current_stage: 'extracting',
available_actions: ['cancel'],
lock_version: 1,
events: [
{
@@ -113,11 +114,35 @@ describe('ShippingWorkflowItemDetailDrawer', () => {
wrapper.unmount();
});
it('does not infer any write or lifecycle entry from a local file status', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({
lifecycle_status: 'pending_review',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
// 空动作契约表示后端没有授予操作;状态名不得让前端补造入口。
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-action-open-review"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
expect(drawerRoot()?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
wrapper.unmount();
});
it('hides cancel for closed items and emits close', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'closed', closed_reason: 'user_cancelled' }),
item: buildItem({
lifecycle_status: 'closed',
closed_reason: 'user_cancelled',
available_actions: [],
}),
},
global: { plugins: [i18n] },
attachTo: document.body,
@@ -52,17 +52,13 @@ const events = computed((): ShippingWorkflowEvent[] => (
const canCancel = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('cancel') || Boolean(props.item);
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
// [AUTHORITY] 文件动作只能由文档级 available_actions 授权;空数组就是明确无权限。
return Array.isArray(actions) && actions.includes('cancel');
});
const canReparse = computed(() => {
const actions = props.item?.available_actions;
if (Array.isArray(actions)) return actions.includes('reparse')
|| ['failed', 'reparse_failed'].includes(String(props.item?.lifecycle_status || '').trim());
// 无契约时 fail-closed,禁止仅凭 pending_review 展示。
return false;
return Array.isArray(actions) && actions.includes('reparse');
});
const reparseActionLabel = computed(() => {
@@ -75,13 +71,8 @@ const reparseActionLabel = computed(() => {
const canOpenReview = computed(() => {
if (!props.item) return false;
const actions = props.item.available_actions;
const status = String(props.item.lifecycle_status || '').trim();
if (Array.isArray(actions)) {
return actions.includes('view_details')
|| actions.includes('enter_manual_review')
|| status === 'pending_review';
}
return status === 'pending_review';
// 生命周期工作台是独立授权,详情/人工复核动作不得隐式升级为生命周期入口。
return Array.isArray(actions) && actions.includes('open_order_review');
});
const filename = computed(() => {
File diff suppressed because it is too large. Load diff
@@ -1,48 +1,50 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「批次进度中心」——OT 任务卡 + 按需展开的文件明细。
* 用途:聊天页右侧「批次进度中心」——后端批次投影、四阶段进度和文件行操作。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow、ShippingConversationProcessingCard、
* conversationProcessingProjection、DetailDrawer、ReasonDialog、ProcessGateRecoveryCard。
* ReasonDialog、ProcessGateRecoveryCard。
* 逻辑:顶层以 OT / ShippingProcessing 为主路径;标题栏仅保留批次名称、加载与截断提示,
* 文件总览和进度仅消费后端批次 summary;
* mapUserTaskObjectsToFileRows 合成文件行;取消/重识别走 Run API;
* 文件清单消费后端 conversation_processing.status_groups;work_items 仅用于定位同一
* 展示 DTO 的操作对象;整批操作走 Run API,单文件取消走 Unit API;
* 路由 focus_task_no / 服务端 focused_task_no 驱动本地选中卡;
* 详情抽屉仅用列表投影,不再请求 WorkflowItem 详情 API。
* 前端只投影后端阶段与授权动作,不保留文件详情抽屉或本地阶段回退。
*/
<script setup lang="ts">
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 {
downloadWorkspaceShippingExcelFile,
downloadWorkspaceShippingExportArchive,
} 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,
cancelWorkspaceShippingOrderExtractionDocument,
reparseWorkspaceShippingOrderExtractionRun,
retryWorkspaceShippingOrderExtractionRun,
retryShippingNoticeIntake,
} from '@/features/chat/api/shipping.api';
import type {
ConversationProcessingUserTask,
LifecycleWorkbenchStage,
ShippingProcessingLifecycleEntry,
ShippingProcessingProjection,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
mapUserTaskObjectsToFileRows,
resolveItemDisplayStatus,
} from '@/features/chat/shipping/conversationProcessingProjection';
import { resolveShippingProcessingMessage } from '@/features/chat/shipping/shippingProcessingLabels';
resolveShippingProcessingMessage,
} from '@/features/chat/shipping/shippingProcessingLabels';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
type UseShippingNoticeWorkflowReturn,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import ShippingConversationProcessingCard from './ShippingConversationProcessingCard.vue';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import ShippingWorkflowReasonDialog, {
type ShippingWorkflowReasonAction,
} from './ShippingWorkflowReasonDialog.vue';
@@ -72,13 +74,6 @@ const gateNavigationContext = computed(() => ({
}));
const { submitPrimaryAction: submitGatePrimaryAction } = useShippingProcessGateRecovery();
/**
* Gate「确认客户」:打开对话叠层客户选择弹窗(非跳转复核)。
*/
async function onGateConfirmCustomer(taskNo: string) {
await chatPage?.openShippingCustomerDialog?.(taskNo);
}
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
@@ -101,29 +96,25 @@ const collapsed = ref(false);
/** 复核返回对话时展示的聚焦提示(由 focus_notice 触发一次)。 */
const focusTaskBanner = ref<string | null>(null);
const actionBusyItemNo = ref<string | null>(null);
const detailOpen = ref(false);
const detailLoading = ref(false);
const detailItem = ref<ShippingWorkflowItem | null>(null);
const reasonDialogOpen = ref(false);
const reasonDialogAction = ref<ShippingWorkflowReasonAction>('cancel');
const reasonDialogItem = ref<ShippingWorkflowItem | null>(null);
/** 任务级取消:走 Run API,不绑单个 WorkflowItem。 */
const reasonDialogRunNo = ref<string | null>(null);
/** 移除右侧常驻批次与文件列表:文件明细改为进入订单处理工作台后展示。 */
const expandedTask = ref<ConversationProcessingUserTask | null>(null);
/** 文件行仅用于 Gate 恢复卡、路由聚焦匹配 activeItem 与 open_review 动作兜底。 */
const items = computed((): ShippingWorkflowItem[] => (
mapUserTaskObjectsToFileRows(expandedTask.value)
));
/** 单文件取消:仅由后端 cancel_unit 授权的 document_id 赋值。 */
const reasonDialogDocumentId = ref<number | null>(null);
const processingWorkItems = computed((): ShippingProcessingProjection[] => (
Array.isArray(ctl.value.processingWorkItems?.value)
? ctl.value.processingWorkItems.value
: []
));
const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
const batchArtifacts = computed(() => displayProcessing.value?.output_artifacts || []);
const batchFourStageNodes = computed(() => displayProcessing.value?.four_stage_nodes || []);
const lifecycleFilter = ref<'all' | 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete'>('all');
const fileSearchQuery = ref('');
const selectedDownloadTaskNos = ref<string[]>([]);
/** 四阶段后端编码为 snake_case,语言资源键沿用 camelCase;映射仅做展示翻译,不参与状态裁决。 */
const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
intake_parse: 'intakeParse',
@@ -134,6 +125,36 @@ const BATCH_FOUR_STAGE_I18N_KEYS: Record<string, string> = {
function batchFourStageLabelKey(code: string): string {
return BATCH_FOUR_STAGE_I18N_KEYS[code] || code;
}
function selectLifecycleFilter(code: 'intake_parse' | 'order_review' | 'fulfillment_prep' | 'upload_complete') {
lifecycleFilter.value = lifecycleFilter.value === code ? 'all' : code;
}
/** 阶段卡仅展示后端统计总数;状态、阻塞和推进语义由颜色与边框表达。 */
function stageTotalText(node: NonNullable<typeof batchFourStageNodes.value>[number]): string {
return String(Number(node.summary?.total || 0));
}
/** 下载资格仅来自后端 output_artifacts 的授权动作;筛选仅影响展示,不缩减授权集合。 */
const downloadableTaskNos = computed(() => {
return [...new Set(batchArtifacts.value
.filter((artifact) => artifact.action?.enabled)
.map((artifact) => String(artifact.order_task_no || '').trim())
.filter(Boolean))];
});
const allDownloadableSelected = computed(() => (
downloadableTaskNos.value.length > 0
&& downloadableTaskNos.value.every((taskNo) => selectedDownloadTaskNos.value.includes(taskNo))
));
watch(downloadableTaskNos, (taskNos) => {
selectedDownloadTaskNos.value = selectedDownloadTaskNos.value.filter((taskNo) => taskNos.includes(taskNo));
}, { immediate: true });
function toggleDownloadSelection(taskNo: string) {
if (!downloadableTaskNos.value.includes(taskNo)) return;
selectedDownloadTaskNos.value = selectedDownloadTaskNos.value.includes(taskNo)
? selectedDownloadTaskNos.value.filter((value) => value !== taskNo)
: [...selectedDownloadTaskNos.value, taskNo];
}
function toggleAllDownloadSelections() {
selectedDownloadTaskNos.value = allDownloadableSelected.value ? [] : [...downloadableTaskNos.value];
}
async function downloadBatchArtifact(taskNo: string) {
if (!taskNo) return;
try {
@@ -142,25 +163,29 @@ async function downloadBatchArtifact(taskNo: string) {
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 }));
await downloadBatchArchive(downloadableTaskNos.value);
}
async function downloadSelectedBatchArtifacts() {
await downloadBatchArchive(selectedDownloadTaskNos.value.filter((taskNo) => downloadableTaskNos.value.includes(taskNo)));
}
async function downloadBatchArchive(taskNos: string[]) {
if (!taskNos.length) return;
try {
const { blob, filename } = await downloadWorkspaceShippingExportArchive({ task_nos: taskNos });
const objectUrl = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = objectUrl;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(objectUrl);
} catch (err) {
msg.error(err instanceof Error ? err.message : t('chat.shippingProcessing.batchWorkbench.artifacts.downloadFailed', { count: taskNos.length }));
}
}
const processing = computed(() => ctl.value.processing?.value ?? null);
/** 展示投影:统一 ShippingProcessing / conversation_processing。 */
const displayProcessing = computed(() => processing.value);
/**
* 批次总览一律按文件计数。会话 summary 中 processing/needs_action 是任务数,
* 不能直接填入原型的“处理中/需处理”文件统计卡。
@@ -248,45 +273,6 @@ 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
|| focusTaskBanner.value
|| displayProcessing.value?.focused_task_no
|| '',
).trim());
/**
* 当前阶段摘要优先跟随路由/服务端聚焦 OT 对应文件行,再回退首个活跃项。
*/
const activeItem = computed(() => {
const focus = routeFocusedTaskNo.value;
if (focus) {
const matched = items.value.find((item) => {
const userTask = String(item.user_task_no || '').trim();
const itemNo = String(item.item_no || '').trim();
return userTask === focus || itemNo === focus;
});
if (matched) return matched;
}
return items.value.find((item) => {
const status = resolveItemDisplayStatus(item);
return status === 'layout_parsing' || status === 'extracting' || status === 'building_order'
|| status === 'inventory_matching' || status === 'generating_excel' || status === 'queued';
}) || items.value.find((item) => resolveItemDisplayStatus(item) === 'pending_review') || items.value[0] || null;
});
/** 任务聚合投影存在时隐藏独立「当前阶段」卡,避免三套状态重复(UI-F04)。 */
const showStandaloneCurrentStage = computed(() => {
const projection = displayProcessing.value;
if (!projection) return true;
return !(
projection.needs_action?.length
|| projection.processing?.length
|| projection.completed?.length
|| projection.history?.length
);
});
/**
* 右侧仍有用户必须持续可见的任务时,禁止收起整个处理面板。
* 核心逻辑:处理中 / 待处理 / 未查看完成均属活跃可见任务;无此类任务才允许收起侧栏。
@@ -325,31 +311,6 @@ watch(
* 文件明细进入订单处理工作台后展示;此处仅保留 Gate 卡与独立 DetailDrawer,避免两套投影矛盾与高度抖动。
*/
function itemActivityLabel(item: ShippingWorkflowItem | null): string {
if (!item) return t('chat.shippingProcessing.emptyCompact');
const status = resolveItemDisplayStatus(item);
const key = `chat.shippingProcessing.activity.${status}`;
return te(key) ? t(key) : statusLabel(status);
}
/**
* 打开当前 PDF 对应的订单处理工作台(fileItems 行)。
* 核心逻辑:复用 Run/Case/文档上下文,避免用户重新寻找待处理文件。
*/
async function openReview(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: item.current_document_id,
caseNo: item.current_case_no,
taskNo: item.current_task_no,
});
}
/**
* 从 OT 任务投影打开订单处理工作台(无 fileItems 时的生产路径)。
* 核心逻辑:必须有 run_no;缺失时 toast 提示,禁止静默 return。
@@ -378,6 +339,7 @@ async function pushOrderReviewQuery(input: {
documentId?: number | null;
caseNo?: string | null;
taskNo?: string | null;
lifecycleStage?: LifecycleWorkbenchStage;
}) {
const query: Record<string, string> = {
mode: 'order-review',
@@ -391,6 +353,7 @@ async function pushOrderReviewQuery(input: {
if (conversationId) query.conversation_id = conversationId;
const taskNo = String(input.taskNo || route.query.focus_task_no || '').trim();
if (taskNo) query.focus_task_no = taskNo;
if (input.lifecycleStage) query.lifecycle_stage = input.lifecycleStage;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
@@ -398,14 +361,31 @@ async function pushOrderReviewQuery(input: {
});
}
const counts = computed(() => ({
total: items.value.length,
processing: Number(displayProcessing.value?.summary?.processing || 0),
pending_review: Number(displayProcessing.value?.summary?.needs_action || 0),
waiting_manual_upload: 0,
failed: 0,
completed: Number(displayProcessing.value?.summary?.completed || 0),
}));
/** 聚合任务卡内的文件入口:只接收叶子投影提供的深链上下文。 */
async function onOpenLifecycleStage(payload: {
projection: ShippingProcessingProjection;
entry: ShippingProcessingLifecycleEntry;
}) {
const item = payload.projection;
const entry = payload.entry;
// 文件行深链必须携带后端 lifecycle entry;阶段码本身不构成授权。
if (
entry.targetSurface !== 'order_lifecycle_workbench'
|| (entry.state !== 'current' && entry.state !== 'available')
) return;
const runNo = String(item.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: item.sourceSummary?.documentId,
caseNo: item.caseNo,
taskNo: item.rootOrderTaskNo || item.workItemNo,
lifecycleStage: entry.code,
});
}
/**
/**
@@ -419,31 +399,17 @@ async function onProcessingFocus(taskNo: string) {
}
/**
* 展开文件详情 → 保留本地聚焦并打开文件级详情抽屉。
* 文件明细在工作台展示;此处额外打开详情抽屉供复核线框与测试断言。
* 无 run_no 时 toast 提示,禁止静默 return。
* 旧文件详情入口已下线:批次中心的文件行直接承载阶段入口与更多操作。
*/
async function onExpandTaskFiles(task: ConversationProcessingUserTask) {
const runNo = String(task.run_no || '').trim();
expandedTask.value = task;
// 打开文件明细抽屉:优先选与 run_no 匹配的 item,否则取 items[0] 兜底
if (items.value.length) {
const target = runNo
? items.value.find((row) => String(row.current_run_no || '').trim() === runNo)
: items.value[0];
if (target) {
detailItem.value = target;
detailOpen.value = true;
}
}
// 仅展开本地详情;进入订单处理工作台由抽屉中的显式「打开复核」动作触发。
await onProcessingFocus(task.user_task_no);
}
/**
* 收起文件详情:仅清空本地过滤聚焦态,右侧不再常驻文件长列表。
*/
function onCollapseTaskFiles() {
expandedTask.value = null;
return;
}
/**
@@ -476,8 +442,8 @@ async function onProcessingIntakeAction(payload: {
}
/**
* 任务级权威操作:查看详情 / 复核 / 取消 / 重试失败文件。
* 查看详情仅打开本地抽屉,禁止写 viewed 后重算右侧业务投影。
* 任务级权威操作:聚焦 / 复核 / 整批取消 / 重试。
* 文件详情已下线;所有文件级动作由叶子投影的 fileAction 处理。
*/
async function onProcessingTaskAction(payload: {
task: ConversationProcessingUserTask;
@@ -487,7 +453,7 @@ async function onProcessingTaskAction(payload: {
const task = payload.task;
const runNo = String(task.run_no || '').trim();
if (action === 'view_details') {
onExpandTaskFiles(task);
await onProcessingFocus(task.user_task_no);
return;
}
if (
@@ -496,15 +462,6 @@ async function onProcessingTaskAction(payload: {
|| action === 'open_order_review'
|| action === 'open_order_processing'
) {
const target = items.value.find((item) => (
String(item.current_run_no || '').trim() === runNo
&& resolveItemDisplayStatus(item) === 'pending_review'
)) || items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
if (target) {
await openReview(target);
return;
}
// 无 fileItems 时直接用任务投影打开复核(生产主路径)。
await openReviewFromTask(task);
return;
}
@@ -517,9 +474,7 @@ async function onProcessingTaskAction(payload: {
msg.warning(t('chat.shippingOrderReview.caseRequired'));
return;
}
const target = items.value.find((item) => String(item.current_run_no || '').trim() === runNo);
if (target) openReparseDialog(target);
else msg.warning(t('chat.shippingOrderReview.caseRequired'));
openReparseRunDialog(runNo);
return;
}
if (action === 'retry_parse' || action === 'retry') {
@@ -577,25 +532,6 @@ async function onProcessingTaskAction(payload: {
}
}
/**
* 列表主标题:优先文件名。
*/
function itemTitle(item: ShippingWorkflowItem): string {
const filename = String(item.current_document_filename || '').trim();
if (filename) return filename;
return t('chat.shippingProcessing.filenameFallback', {
docId: item.current_document_id,
});
}
/**
* 解析生命周期状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingProcessing.itemStatus.${status}`;
return te(key) ? t(key) : t('chat.shippingProcessing.itemStatus.unknown');
}
/**
* 手动刷新。
*/
@@ -606,35 +542,43 @@ async function onRefresh() {
/**
* 打开取消原因弹窗:优先绑定 current_run_no,走 Run 级取消 API。
*/
function openCancelDialog(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
reasonDialogItem.value = item;
reasonDialogRunNo.value = runNo || null;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开任务级取消原因弹窗(Run 级 API)。
*/
function openCancelRunDialog(runNo: string) {
reasonDialogItem.value = null;
reasonDialogRunNo.value = String(runNo || '').trim() || null;
reasonDialogDocumentId.value = null;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开重识别原因弹窗:优先绑定 current_run_no,走 Run 级 reparse API。
* 打开重识别原因弹窗:走 Run 级 reparse API。
*/
function openReparseDialog(item: ShippingWorkflowItem) {
const runNo = String(item.current_run_no || '').trim();
reasonDialogItem.value = item;
reasonDialogRunNo.value = runNo || null;
function openReparseRunDialog(runNo: string) {
reasonDialogRunNo.value = String(runNo || '').trim() || null;
reasonDialogDocumentId.value = null;
reasonDialogAction.value = 'reparse';
reasonDialogOpen.value = true;
}
/**
* 文件级取消:只能接受后端叶子投影明确授予的 cancel_unit。
*/
function onProcessingFileAction(payload: {
projection: ShippingProcessingProjection;
action: string;
}) {
if (payload.action !== 'cancel_unit') return;
const runNo = String(payload.projection.runNo || '').trim();
const documentId = Number(payload.projection.sourceSummary?.documentId || 0);
if (!runNo || documentId <= 0) {
msg.warning(t('chat.shippingProcessing.cancelTaskMissingRun'));
return;
}
reasonDialogRunNo.value = runNo;
reasonDialogDocumentId.value = documentId;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 将重新识别失败转换为可执行提示,而不是直接展示内部配置错误。
* @param error - API 层 BusinessError 或未知异常
@@ -666,12 +610,11 @@ function reparseErrorMessage(error: unknown): { title: string; message: string }
}
/**
* 原因弹窗确认:取消/重识别一律走订单抽取 Run API(不再调用 Workflow Item ledger)。
* 原因弹窗确认:单文件取消走 Unit API;整批取消与重识别走 Run API。
*/
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
const runNo = String(reasonDialogRunNo.value || reasonDialogItem.value?.current_run_no || '').trim();
const item = reasonDialogItem.value;
const itemNo = String(item?.item_no || '').trim();
const runNo = String(reasonDialogRunNo.value || '').trim();
const documentId = reasonDialogDocumentId.value;
if (!runNo || actionBusyItemNo.value) return;
actionBusyItemNo.value = runNo;
try {
@@ -688,23 +631,21 @@ async function onReasonConfirm(payload: { reason: string; comment?: string }) {
comment,
});
} else {
await cancelWorkspaceShippingOrderExtractionRun(runNo, {
reason: payload.reason,
});
if (documentId && documentId > 0) {
await cancelWorkspaceShippingOrderExtractionDocument(runNo, documentId, { reason: payload.reason });
} else {
await cancelWorkspaceShippingOrderExtractionRun(runNo, { reason: payload.reason });
}
}
await ctl.value.refresh();
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
reasonDialogRunNo.value = null;
if (itemNo && detailItem.value?.item_no === itemNo) {
detailOpen.value = false;
detailItem.value = null;
}
reasonDialogDocumentId.value = null;
} catch (err) {
// 失败时关闭原因确认框,避免与错误提示双遮罩。
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
reasonDialogRunNo.value = null;
reasonDialogDocumentId.value = null;
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
@@ -723,12 +664,55 @@ async function onTaskProjectionAction(payload: {
const { projection, item } = payload;
const taskNo = String(projection.workItemNo || '').trim();
const code = String(item.actionCode || '').trim();
/**
* 跳转目标完全由后端 ui_state 声明;必须匹配用户实际点击的主/次动作。
* 否则次动作虽已完成 Projection 透传,仍会误落入旧的“查看结果”处理分支。
*/
const authoritativeAction = [
projection.uiState?.primary_action,
...(projection.uiState?.secondary_actions || []),
].find((action) => (
action?.code === code
&& action.executionMode === 'navigate'
&& action.targetSurface === 'order_lifecycle_workbench'
&& action.targetLifecycleStage
));
if (
authoritativeAction?.code === code
&& authoritativeAction.executionMode === 'navigate'
&& authoritativeAction.targetSurface === 'order_lifecycle_workbench'
&& authoritativeAction.targetLifecycleStage
) {
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
await pushOrderReviewQuery({
runNo,
documentId: projection.sourceSummary?.documentId,
caseNo: projection.caseNo,
taskNo: projection.rootOrderTaskNo || taskNo,
lifecycleStage: authoritativeAction.targetLifecycleStage,
});
return;
}
if (code === 'reparse') {
const task = [
...(displayProcessing.value?.needs_action || []),
...(displayProcessing.value?.processing || []),
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) void onProcessingTaskAction({ task, action: 'reparse' });
if (task) {
void onProcessingTaskAction({ task, action: 'reparse' });
return;
}
// 文件叶子没有父任务同名 workItemNo;仅使用后端下发的当前 Run,不反推任务或阶段。
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
return;
}
openReparseRunDialog(runNo);
return;
}
if (code === 'retry_inventory_preparation') {
@@ -747,8 +731,26 @@ async function onTaskProjectionAction(payload: {
}
return;
}
if (code === 'retry_parse' || item.intent === 'retry') {
void onProcessingIntakeAction({ item: projection, action: code || 'retry_parse' });
if (code === 'retry_parse') {
void onProcessingIntakeAction({ item: projection, action: code });
return;
}
if (code === 'retry' || item.intent === 'retry') {
const runNo = String(projection.runNo || '').trim();
if (!runNo) {
msg.warning(t('chat.shippingProcessing.retryTaskMissingRun'));
return;
}
if (actionBusyItemNo.value) return;
actionBusyItemNo.value = runNo;
try {
await retryWorkspaceShippingOrderExtractionRun(runNo);
await ctl.value.refresh();
} catch (err) {
msg.error(reparseErrorMessage(err));
} finally {
actionBusyItemNo.value = null;
}
return;
}
if (item.intent === 'refresh') {
@@ -788,17 +790,21 @@ async function onTaskProjectionAction(payload: {
].find((row) => String(row.user_task_no || '').trim() === taskNo);
if (task) {
await onProcessingFocus(taskNo);
await onExpandTaskFiles(task);
return;
}
// 未获得后端导航目标且无法关联父任务时,必须可见地失败,禁止静默无响应。
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
return;
}
if (item.intent === 'open_manual_upload' && taskNo) {
void router.push({
name: 'workspace-shipping-my-tasks',
query: { task_no: taskNo },
query: { task_no: projection.rootOrderTaskNo || taskNo },
});
return;
}
// 其余 intent 由任务卡/ Gate 卡片承载,此处安全 no-op。
// 未注册的旧动作不得静默吞掉,也不在此处伪造业务写操作。
msg.warning(t('chat.shippingProcessing.batchWorkbench.fileEntries.unavailable'));
}
watch(
@@ -906,8 +912,8 @@ watch(
</template>
<template v-else>
{{ t('chat.shippingProcessing.compactSummary', {
active: items.length,
total: counts.total,
active: 0,
total: 0,
}) }}
</template>
</div>
@@ -962,48 +968,34 @@ watch(
</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>
<button v-for="node in batchFourStageNodes" :key="node.code" type="button" class="rounded-lg border px-2 py-2 text-left text-xs transition-colors" :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', lifecycleFilter === node.code ? 'ring-2 ring-brand-400 ring-offset-1' : 'hover:brightness-95']" :data-testid="`shipping-workflow-stage-filter-${node.code}`" @click="selectLifecycleFilter(node.code)">
<span class="block font-semibold">{{ t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(node.code)}`) }}</span>
<span class="mt-0.5 block text-[11px] opacity-80">{{ stageTotalText(node) }}</span>
</button>
</div>
<div v-if="lifecycleFilter !== 'all'" class="mt-2 flex items-center justify-between gap-2 text-xs text-secondary">
<span>{{ t('chat.shippingProcessing.batchWorkbench.filteringByStage', { stage: t(`chat.shippingNoticeUi.stage.${batchFourStageLabelKey(lifecycleFilter)}`) }) }}</span>
<button type="button" class="text-brand-700 hover:underline" data-testid="shipping-workflow-clear-stage-filter" @click="lifecycleFilter = 'all'">{{ t('chat.shippingProcessing.batchWorkbench.clearStageFilter') }}</button>
</div>
<p v-if="Number(displayProcessing?.unclassified_summary?.count || 0) > 0" class="mt-2 text-xs text-amber-700" data-testid="shipping-workflow-unclassified-summary">
{{ t('chat.shippingProcessing.batchWorkbench.unclassified', { count: displayProcessing?.unclassified_summary?.count }) }}
</p>
</section>
<section
class="mb-4 rounded-xl border border-default bg-surface p-4"
data-testid="shipping-workflow-batch-artifacts"
class="mb-3 flex flex-wrap items-center justify-between gap-2 rounded-xl border border-default bg-surface px-3 py-2"
data-testid="shipping-workflow-file-toolbar"
>
<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>
<label class="relative block min-w-48 flex-1 sm:max-w-sm">
<span class="sr-only">{{ t('chat.shippingProcessing.batchWorkbench.search.label') }}</span>
<input v-model="fileSearchQuery" type="search" class="w-full rounded-md border border-default bg-surface px-2.5 py-1.5 text-xs" :placeholder="t('chat.shippingProcessing.batchWorkbench.search.placeholder')" data-testid="shipping-workflow-file-search">
</label>
<div v-if="lifecycleFilter === 'upload_complete' && downloadableTaskNos.length" class="flex flex-wrap items-center gap-2" data-testid="shipping-workflow-download-toolbar">
<label class="inline-flex items-center gap-1 text-xs text-secondary"><input type="checkbox" :checked="allDownloadableSelected" data-testid="shipping-workflow-download-select-all" @change="toggleAllDownloadSelections"><span>{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selectAll') }}</span></label>
<span class="text-xs text-secondary">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.selected', { count: selectedDownloadTaskNos.length }) }}</span>
<button type="button" class="rounded-md border border-brand-300 px-2.5 py-1 text-xs font-medium text-brand-700 disabled:opacity-50" :disabled="!selectedDownloadTaskNos.length" data-testid="shipping-workflow-download-selected" @click="downloadSelectedBatchArtifacts">{{ t('chat.shippingProcessing.batchWorkbench.artifacts.downloadSelected') }}</button>
<button type="button" class="rounded-md bg-brand-600 px-2.5 py-1 text-xs font-medium text-white disabled:opacity-50" :disabled="!downloadableTaskNos.length" data-testid="shipping-workflow-download-all" @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
@@ -1020,29 +1012,22 @@ watch(
:work-items="processingWorkItems"
:conversation-id="conversationId"
:workbench-mode="true"
:lifecycle-filter="lifecycleFilter"
:file-search-query="fileSearchQuery"
:downloadable-task-nos="downloadableTaskNos"
:selected-download-task-nos="selectedDownloadTaskNos"
:has-more-history="Boolean(displayProcessing?.summary?.has_more_history)"
@expand-files="onExpandTaskFiles"
@collapse-files="onCollapseTaskFiles"
@task-action="(payload) => void onProcessingTaskAction(payload)"
@intake-action="(payload) => void onProcessingIntakeAction(payload)"
@projection-action="onTaskProjectionAction"
@file-action="onProcessingFileAction"
@download-artifact="downloadBatchArtifact"
@toggle-download-selection="toggleDownloadSelection"
@open-lifecycle-stage="onOpenLifecycleStage"
/>
<section
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"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="text-[11px] font-medium uppercase tracking-wide text-brand-700 dark:text-brand-300">{{ t('chat.shippingProcessing.activity.currentStageTitle') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ itemActivityLabel(activeItem) }}</div>
<div v-if="activeItem" class="mt-1 truncate text-[11px] text-secondary">{{ itemTitle(activeItem) }}</div>
</div>
<span class="shrink-0 rounded-full bg-white/80 px-2 py-1 text-[11px] font-medium text-brand-700 dark:bg-slate-900/60 dark:text-brand-200">{{ activeItem ? statusLabel(resolveItemDisplayStatus(activeItem)) : t('chat.shippingProcessing.emptyCompact') }}</span>
</div>
</section>
<div
v-if="error === 'network_recoverable'"
class="mb-3 rounded-md border border-amber-200 bg-amber-50 px-2.5 py-2 text-[11px] text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
@@ -1057,66 +1042,8 @@ watch(
{{ error }}
</div>
<!-- 侧栏内直接展示阻断 Gate 与文件明细,避免重复弹层。 -->
<div
v-if="!displayProcessing"
class="space-y-2"
data-testid="shipping-workflow-compact-gates"
>
<ProcessGateRecoveryCard
v-for="item in items.filter((row) => row.process_gate?.current_blocking_gate)"
:key="`gate-${item.item_no}`"
:summary="item.process_gate"
:can-handle="true"
:navigation-context="gateNavigationContext"
@refreshed="() => void ctl.refresh()"
@refresh-needed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
</div>
<!-- 聚焦任务下的文件行列表:供跨 Run 合并与文件筛选断言。 -->
<ul
v-if="!displayProcessing && expandedTask && items.length"
class="my-3 space-y-1.5"
>
<li
v-for="row in items"
:key="row.item_no"
class="rounded-lg border border-default bg-surface px-2.5 py-2 text-[11px] text-secondary"
:data-testid="`shipping-workflow-item-${row.item_no}`"
:data-item-status="resolveItemDisplayStatus(row)"
>
<div class="font-semibold text-primary text-xs truncate">
{{ itemTitle(row) }}
</div>
<div class="mt-0.5 truncate">
{{ statusLabel(resolveItemDisplayStatus(row)) }}
</div>
</li>
</ul>
</div>
<!--
方案 7:移除右侧常驻「批次与文件列表」聚合抽屉,避免与任务卡投影矛盾与高度抖动。
文件明细统一在订单处理工作台展示;任务卡仅显示任务名 / 文件数 / 状态 / 主按钮。
Gate 级阻断与进度详情仍通过 ProcessGateRecoveryCard 与 ShippingWorkflowItemDetailDrawer 呈现。
-->
<ShippingWorkflowItemDetailDrawer
:open="detailOpen"
:item="detailItem"
:loading="detailLoading"
:cancelling="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'cancel')"
:reparsing="Boolean(detailItem && actionBusyItemNo === detailItem.item_no && reasonDialogAction === 'reparse')"
@close="detailOpen = false; detailItem = null"
@cancel="openCancelDialog"
@reparse="openReparseDialog"
@open-review="(row) => openReview(row)"
@refreshed="() => void ctl.refresh()"
@confirm-customer="(taskNo) => void onGateConfirmCustomer(taskNo)"
/>
<ShippingWorkflowReasonDialog
v-model="reasonDialogOpen"
:action="reasonDialogAction"