feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验

- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全
- 引入审计事件的哈希链校验机制,支持数据完整性验证
- 增强订单抽取与审计功能,支持敏感快照的访问控制
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-31 08:59:44 +08:00
1 parent 95cdfe66b0
commit d0fe084999
225 files changed
+25923 -6653

No files matched your search

@@ -2,18 +2,18 @@
* features/chat/components/ChatViewContent.vue
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话任务摘要与内置浏览器。
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话 Workflow 时间线与内置浏览器。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingSessionSummaryPanel、chat.context。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingWorkflowTimeline、chat.context。
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;
* 右侧「本次处理」由 conversationId 驱动 session-work-items,extractionRunNo 仅作进度装饰。
* 右侧「本次处理」由 conversationId 驱动 Workflow projection,extractionRunNo 仅作进度装饰。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { computed, provide, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
@@ -31,7 +31,7 @@ import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingSessionSummaryPanel from '@/features/chat/components/ShippingSessionSummaryPanel.vue';
import ShippingWorkflowTimeline from '@/features/chat/components/shipping/ShippingWorkflowTimeline.vue';
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
@@ -47,6 +47,11 @@ import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
@@ -77,6 +82,13 @@ type MaintenanceRecordPanelCommand = {
const page = useChatPageContext();
const shippingWorkflow = useShippingNoticeWorkflow({
conversationId: () => page.conversationId,
refreshTrigger: () => page.workflowRefreshTrigger,
});
provide(SHIPPING_WORKFLOW_KEY, shippingWorkflow);
const route = useRoute();
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
@@ -139,7 +151,7 @@ const activeExtractionRunNo = computed(() => {
const showShippingSessionSummary = computed(() => (
const showShippingWorkflowTimeline = computed(() => (
page.isShippingNoticeAgent
&& Boolean(
page.conversationId
@@ -655,26 +667,11 @@ watch(() => page.currentAgentId, () => {
<ShippingSessionSummaryPanel
v-if="showShippingSessionSummary"
<ShippingWorkflowTimeline
v-if="showShippingWorkflowTimeline"
:conversation-id="page.conversationId"
:conversation-workspace="page.shippingConversationWorkspace"
:active-batch-no="page.activeShippingBatchNo"
:batch-summary="page.shippingBatchSummary"
:batch-tasks="page.shippingBatchTasks"
:active-task-detail="page.activeShippingTaskDetail"
:extraction-run-no="activeExtractionRunNo"
:refresh-trigger="page.sessionWorkItemsRefreshTrigger"
:refresh-trigger="page.workflowRefreshTrigger"
:controller="shippingWorkflow"
/>
@@ -1,174 +0,0 @@
/**
* features/chat/components/ShippingSessionSummaryPanel.spec.ts
* 用途:验证右侧「本次处理」以 session-work-items 为列表事实源。
* 依赖:Vitest、Vue Test Utils、vue-i18n、vue-router、shipping.api mock。
* 逻辑:断言两次重识别后仍展示 2 条 open 项;已关闭分组默认折叠。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createI18n } from 'vue-i18n';
import { createRouter, createMemoryHistory } from 'vue-router';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingSessionSummaryPanel from './ShippingSessionSummaryPanel.vue';
import type { ShippingSessionWorkItemSummary } from '../types/shipping.api.types';
vi.mock('@/features/chat/api/shipping.api', () => ({
listWorkspaceShippingSessionWorkItems: vi.fn(),
listWorkspaceShippingSessionWorkItemVersions: vi.fn(),
getWorkspaceShippingOrderExtractionRun: vi.fn(),
closeWorkspaceShippingSessionWorkItem: vi.fn(),
markWorkspaceShippingOrderReviewNonOrder: vi.fn(),
reparseWorkspaceShippingOrderReviewDocument: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}),
}));
import {
getWorkspaceShippingOrderExtractionRun,
listWorkspaceShippingSessionWorkItems,
} from '@/features/chat/api/shipping.api';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } }],
});
const buildWorkbench = (patch: Partial<ShippingSessionWorkItemSummary> = {}): ShippingSessionWorkItemSummary => ({
conversation_id: 'conv-1',
open_count: 2,
closed_count: 1,
pending_review_count: 2,
extracting_count: 0,
open_items: [
{
item_no: 'SWI-001',
conversation_id: 'conv-1',
owner_user_id: 1,
root_document_id: 10,
current_document_id: 10,
current_document_filename: 'PO-A.pdf',
current_run_no: 'SNER-1',
current_case_no: 'SNRC-1',
current_version_no: 1,
lifecycle_status: 'pending_review',
lock_version: 1,
available_actions: [
'enter_manual_review',
'view_version_history',
'request_reparse',
'mark_non_order',
'cancel',
'replace_file',
],
},
{
item_no: 'SWI-002',
conversation_id: 'conv-1',
owner_user_id: 1,
root_document_id: 11,
current_document_id: 11,
current_document_filename: 'PO-B.pdf',
current_run_no: 'SNER-2',
current_case_no: 'SNRC-2',
current_version_no: 2,
lifecycle_status: 'pending_review',
lock_version: 2,
version_replaced: true,
available_actions: [
'enter_manual_review',
'view_version_history',
'request_reparse',
'mark_non_order',
'cancel',
'replace_file',
],
},
],
closed_items: [
{
item_no: 'SWI-003',
conversation_id: 'conv-1',
owner_user_id: 1,
root_document_id: 12,
current_document_id: 12,
current_document_filename: 'PO-C.pdf',
current_version_no: 1,
lifecycle_status: 'closed',
closed_reason: 'confirmed',
lock_version: 1,
available_actions: ['view_version_history'],
},
],
closed_collapsed: true,
max_open_items: 50,
truncated: false,
...patch,
});
describe('ShippingSessionSummaryPanel', () => {
beforeEach(() => {
vi.mocked(listWorkspaceShippingSessionWorkItems).mockReset();
vi.mocked(getWorkspaceShippingOrderExtractionRun).mockReset();
vi.mocked(getWorkspaceShippingOrderExtractionRun).mockResolvedValue(null as never);
});
it('shows two open work items after two reparses mock', async () => {
vi.mocked(listWorkspaceShippingSessionWorkItems).mockResolvedValue(buildWorkbench());
const wrapper = mount(ShippingSessionSummaryPanel, {
props: {
conversationId: 'conv-1',
conversationWorkspace: null,
activeBatchNo: '',
batchSummary: null,
batchTasks: [],
activeTaskDetail: null,
},
global: { plugins: [i18n, router] },
});
await flushPromises();
const rows = wrapper.findAll('[data-testid^="shipping-session-work-item-"]');
expect(rows.length).toBe(2);
expect(wrapper.text()).toContain('PO-A.pdf');
expect(wrapper.text()).toContain('PO-B.pdf');
expect(wrapper.text()).toContain('V2');
expect(wrapper.text()).toContain('已生成新版本');
expect(wrapper.findAll('[data-testid="shipping-session-action-cancel"]').length).toBe(2);
expect(wrapper.findAll('[data-testid="shipping-session-action-non-order"]').length).toBe(2);
expect(wrapper.findAll('[data-testid="shipping-session-action-reparse"]').length).toBe(2);
expect(wrapper.findAll('[data-testid="shipping-session-action-replace"]').length).toBe(2);
});
it('keeps closed section collapsed by default', async () => {
vi.mocked(listWorkspaceShippingSessionWorkItems).mockResolvedValue(buildWorkbench());
const wrapper = mount(ShippingSessionSummaryPanel, {
props: {
conversationId: 'conv-1',
conversationWorkspace: null,
activeBatchNo: '',
batchSummary: null,
batchTasks: [],
activeTaskDetail: null,
},
global: { plugins: [i18n, router] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-session-closed-section"]').exists()).toBe(true);
expect(wrapper.text()).toContain('已完成 1 项');
expect(wrapper.text()).not.toContain('PO-C.pdf');
await wrapper.find('[data-testid="shipping-session-closed-section"] button').trigger('click');
expect(wrapper.text()).toContain('PO-C.pdf');
});
});
@@ -1,720 +0,0 @@
/**
* features/chat/components/ShippingSessionSummaryPanel.vue
* 用途:聊天页右侧「本次处理」面板——以会话级 PDF 工作项 API 为唯一列表事实源。
* 依赖:vue-i18n、vue-router、shipping.api session-work-items / 复核处置、useMessage。
* 逻辑:conversationId 驱动 listWorkspaceShippingSessionWorkItems 轮询;extractionRunNo 仅作 Run 级处理事项装饰;
* 按 available_actions 渲染人工复核/版本历史/取消/非订单/重识别/替换文件入口。
*/
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight, ExternalLink } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
closeWorkspaceShippingSessionWorkItem,
getWorkspaceShippingOrderExtractionRun,
listWorkspaceShippingSessionWorkItemVersions,
listWorkspaceShippingSessionWorkItems,
markWorkspaceShippingOrderReviewNonOrder,
reparseWorkspaceShippingOrderReviewDocument,
type ShippingBatchSummary,
type ShippingConversationWorkspace,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import type {
ShippingOrderExtractionRun,
ShippingSessionWorkItem,
ShippingSessionWorkItemSummary,
ShippingSessionWorkItemVersion,
} from '@/features/chat/types/shipping.api.types';
import {
listDisplayableHandlingAffectedRefs,
type ShippingHandlingAffectedRef,
type ShippingHandlingRefTarget,
} from '@/features/chat/shipping/orderExtractionHandlingRefs';
const props = defineProps<{
/** 当前聊天会话 ID;工作项列表的唯一驱动键。 */
conversationId?: string | null;
conversationWorkspace: ShippingConversationWorkspace | null;
activeBatchNo: string;
batchSummary: ShippingBatchSummary | null;
batchTasks: ShippingTaskSummary[];
activeTaskDetail: ShippingTaskDetail | null;
/** 可选:当前活跃抽取 Run,仅用于 Run 级 handling_items 装饰,不驱动 PDF 列表。 */
extractionRunNo?: string | null;
/** 父级递增以触发立即刷新(终态/重识别/会话恢复后)。 */
refreshTrigger?: number;
}>();
const { t, te, locale } = useI18n();
const route = useRoute();
const router = useRouter();
const msg = useMessage();
const collapsed = ref(false);
const openOnlyFilter = ref(false);
const closedExpanded = ref(false);
const workbench = ref<ShippingSessionWorkItemSummary | null>(null);
const workItemsLoading = ref(false);
const actionBusyItemNo = ref<string | null>(null);
const extractionRun = ref<ShippingOrderExtractionRun | null>(null);
const versionHistoryItemNo = ref<string | null>(null);
const versionHistoryItems = ref<ShippingSessionWorkItemVersion[]>([]);
const versionHistoryLoading = ref(false);
let workItemsTimer: ReturnType<typeof setTimeout> | null = null;
let workItemsPollGeneration = 0;
let workItemsRequestController: AbortController | null = null;
const FOREGROUND_POLL_MS = 2000;
const BACKGROUND_POLL_MS = 8000;
/**
* 按页面可见性选择工作项轮询间隔。
*/
function resolveWorkItemsPollMs(): number {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
return BACKGROUND_POLL_MS;
}
return FOREGROUND_POLL_MS;
}
const normalizedConversationId = computed(() => String(props.conversationId || '').trim());
const handlingItems = computed(() => (
Array.isArray(extractionRun.value?.handling_items)
? extractionRun.value!.handling_items!.filter((item) => String(item.category || '').trim())
: []
));
const openItems = computed((): ShippingSessionWorkItem[] => workbench.value?.open_items || []);
const closedItems = computed((): ShippingSessionWorkItem[] => workbench.value?.closed_items || []);
const displayOpenItems = computed(() => {
if (!openOnlyFilter.value) return openItems.value;
return openItems.value.filter((item) =>
item.lifecycle_status === 'pending_review' || item.lifecycle_status === 'reparse_failed',
);
});
const processSummary = computed(() => ({
total: Number(workbench.value?.open_count || 0) + Number(workbench.value?.closed_count || 0),
completed: Number(workbench.value?.closed_count || 0),
running: Number(workbench.value?.extracting_count || 0),
needsHuman: Number(workbench.value?.pending_review_count || 0),
failed: openItems.value.filter((item) => item.lifecycle_status === 'reparse_failed').length,
pending: 0,
openExisting: 0,
pendingConfirmation: 0,
cancelled: 0,
}));
/**
* 解析 Run 级处理事项标题。
*/
function handlingTitle(category: string): string {
const key = `chat.shippingOrderExtractionHandling.category.${category}`;
return te(key) ? t(key) : category;
}
/**
* 解析原因码文案。
*/
function handlingReasonLabel(code: string): string {
const key = `chat.shippingOrderExtractionReason.${code}`;
if (te(key)) return t(key);
const freezeKey = `chat.shippingOrderExtractionHandling.reason.${code}`;
return te(freezeKey) ? t(freezeKey) : code;
}
/**
* 解析工作项生命周期状态文案。
*/
function lifecycleStatusLabel(status: string): string {
const key = `chat.shippingSessionWorkItem.status.${status}`;
return te(key) ? t(key) : status;
}
/**
* 解析工作项关闭原因文案。
*/
function closedReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingSessionWorkItem.closedReason.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 格式化 updated_at 为「更新于 HH:mm」。
*/
function formatUpdatedLabel(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
}
/**
* 拉取会话工作台与可选 Run 装饰数据。
*/
async function refreshWorkItems() {
const conversationId = normalizedConversationId.value;
if (!conversationId || workItemsLoading.value) return;
workItemsLoading.value = true;
workItemsRequestController?.abort();
const controller = new AbortController();
workItemsRequestController = controller;
try {
const [summaryResponse, runResponse] = await Promise.all([
listWorkspaceShippingSessionWorkItems(conversationId, {
open_only: openOnlyFilter.value,
signal: controller.signal,
}),
(() => {
const runNo = String(props.extractionRunNo || '').trim();
return runNo ? getWorkspaceShippingOrderExtractionRun(runNo).catch(() => null) : Promise.resolve(null);
})(),
]);
if (controller.signal.aborted) return;
workbench.value = summaryResponse;
extractionRun.value = runResponse;
if (!closedExpanded.value) {
closedExpanded.value = false;
}
} catch {
/* 右侧失败不打断聊天 */
} finally {
if (workItemsRequestController === controller) {
workItemsRequestController = null;
}
workItemsLoading.value = false;
}
}
function stopWorkItemsPolling() {
if (workItemsTimer) clearTimeout(workItemsTimer);
workItemsTimer = null;
workItemsRequestController?.abort();
workItemsRequestController = null;
workItemsPollGeneration += 1;
}
/**
* 可见性感知的工作项轮询;前台 2s,后台 8s。
*/
function scheduleWorkItemsPoll(generation: number, delayMs: number) {
if (workItemsTimer) clearTimeout(workItemsTimer);
workItemsTimer = setTimeout(async () => {
if (generation !== workItemsPollGeneration) return;
await refreshWorkItems();
if (generation !== workItemsPollGeneration) return;
if (!normalizedConversationId.value) return;
scheduleWorkItemsPoll(generation, resolveWorkItemsPollMs());
}, delayMs);
}
function restartWorkItemsPolling() {
stopWorkItemsPolling();
const conversationId = normalizedConversationId.value;
if (!conversationId) {
workbench.value = null;
extractionRun.value = null;
return;
}
const generation = workItemsPollGeneration;
void refreshWorkItems().then(() => {
if (generation !== workItemsPollGeneration) return;
scheduleWorkItemsPoll(generation, resolveWorkItemsPollMs());
});
}
function onVisibilityChange() {
if (typeof document === 'undefined' || document.visibilityState !== 'visible') return;
if (!normalizedConversationId.value) return;
scheduleWorkItemsPoll(workItemsPollGeneration, 0);
}
/**
* 打开版本历史面板并拉取时间线。
*/
async function openVersionHistory(item: ShippingSessionWorkItem) {
const itemNo = String(item.item_no || '').trim();
if (!itemNo) return;
if (versionHistoryItemNo.value === itemNo) {
versionHistoryItemNo.value = null;
versionHistoryItems.value = [];
return;
}
versionHistoryItemNo.value = itemNo;
versionHistoryLoading.value = true;
try {
const response = await listWorkspaceShippingSessionWorkItemVersions(itemNo);
versionHistoryItems.value = response.versions || [];
} catch {
versionHistoryItems.value = [];
} finally {
versionHistoryLoading.value = false;
}
}
/**
* 打开人工复核(Chat order-review 模式);使用行内 case_no / run_no。
*/
async function openManualReview(item: ShippingSessionWorkItem) {
const runNo = String(item.current_run_no || '').trim();
if (!runNo) return;
const caseNo = String(item.current_case_no || '').trim();
const query: Record<string, string> = {
...Object.fromEntries(
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
),
mode: 'order-review',
run_no: runNo,
};
if (caseNo) query.case = caseNo;
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query,
});
}
/**
* 按 Run 级处理事项受影响对象跳转。
*/
async function openAffectedRef(target: ShippingHandlingRefTarget, runNo?: string) {
if (target.kind === 'task') {
await router.push({
name: 'workspace-shipping-tasks',
params: { taskNo: target.taskNo },
});
return;
}
if (target.kind === 'review') {
const normalizedRun = String(runNo || props.extractionRunNo || '').trim();
if (!normalizedRun) return;
await openManualReview({
item_no: '',
conversation_id: normalizedConversationId.value,
owner_user_id: 0,
root_document_id: 0,
current_document_id: 0,
current_run_no: normalizedRun,
current_case_no: target.documentId ? '' : '',
current_version_no: 1,
lifecycle_status: 'pending_review',
lock_version: 1,
available_actions: [],
});
}
}
/**
* 按处理事项主动作打开复核入口。
*/
async function openHandlingAction(
action?: string | null,
refs?: Array<Record<string, unknown>> | null,
) {
const runNo = String(props.extractionRunNo || '').trim();
if (!runNo) return;
const rows = listDisplayableHandlingAffectedRefs(refs as ShippingHandlingAffectedRef[] | undefined);
const first = rows[0];
if (first) {
await openAffectedRef(first.target, runNo);
return;
}
const normalized = String(action || '').trim();
if (
normalized === 'enter_manual_review'
|| normalized === 'review_candidate'
|| normalized === 'view_details'
|| !normalized
) {
await router.push({
name: 'Chat',
params: { agentId: String(route.params.agentId || '') },
query: {
...Object.fromEntries(
Object.entries(route.query).filter(([, v]) => typeof v === 'string') as Array<[string, string]>,
),
mode: 'order-review',
run_no: runNo,
},
});
}
}
/**
* 提示并收集操作原因;取消输入时返回 null。
*/
function promptActionReason(messageKey: string): string | null {
const reason = window.prompt(t(messageKey));
if (reason == null) return null;
const trimmed = reason.trim();
if (!trimmed) {
msg.warning(t('chat.shippingSessionWorkItem.reasonRequired'));
return null;
}
return trimmed;
}
/**
* 执行工作项写操作后刷新列表;失败用业务错误提示。
*/
async function runWorkItemAction(item: ShippingSessionWorkItem, action: () => Promise<unknown>) {
const itemNo = String(item.item_no || '').trim();
if (!itemNo || actionBusyItemNo.value) return;
actionBusyItemNo.value = itemNo;
try {
await action();
await refreshWorkItems();
} catch (error) {
const message = error instanceof BusinessError ? error.message : t('errors.generic');
msg.error(message);
} finally {
actionBusyItemNo.value = null;
}
}
/**
* 取消本次处理(关闭工作项)。
*/
async function cancelWorkItem(item: ShippingSessionWorkItem) {
const reason = promptActionReason('chat.shippingSessionWorkItem.cancelReasonPrompt');
if (!reason) return;
await runWorkItemAction(item, () => closeWorkspaceShippingSessionWorkItem(String(item.item_no), {
reason,
expected_lock_version: item.lock_version,
}));
}
/**
* 标记非订单并关闭当前 Case/工作项。
*/
async function markNonOrderFromPanel(item: ShippingSessionWorkItem) {
const caseNo = String(item.current_case_no || '').trim();
if (!caseNo) {
msg.warning(t('chat.shippingSessionWorkItem.caseRequired'));
return;
}
const reason = promptActionReason('chat.shippingSessionWorkItem.nonOrderReasonPrompt');
if (!reason) return;
await runWorkItemAction(item, () => markWorkspaceShippingOrderReviewNonOrder(caseNo, 'non_order', reason));
}
/**
* 单文件重新识别。
*/
async function reparseFromPanel(item: ShippingSessionWorkItem) {
const caseNo = String(item.current_case_no || '').trim();
if (!caseNo) {
msg.warning(t('chat.shippingSessionWorkItem.caseRequired'));
return;
}
const reason = promptActionReason('chat.shippingSessionWorkItem.reparseReasonPrompt');
if (!reason) return;
await runWorkItemAction(item, () => reparseWorkspaceShippingOrderReviewDocument(caseNo, 'other', reason));
}
/**
* 替换文件:进入人工复核页完成上传替代流程。
*/
async function replaceFileFromPanel(item: ShippingSessionWorkItem) {
await openManualReview(item);
}
function itemHasAction(item: ShippingSessionWorkItem, action: string): boolean {
return Array.isArray(item.available_actions) && item.available_actions.includes(action);
}
watch(normalizedConversationId, () => restartWorkItemsPolling(), { immediate: true });
watch(openOnlyFilter, () => { void refreshWorkItems(); });
watch(() => props.refreshTrigger, () => {
if (!normalizedConversationId.value) return;
scheduleWorkItemsPoll(workItemsPollGeneration, 0);
});
watch(() => props.extractionRunNo, () => { void refreshWorkItems(); });
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', onVisibilityChange);
}
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', onVisibilityChange);
}
stopWorkItemsPolling();
});
</script>
<template>
<aside
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
data-testid="shipping-session-summary"
>
<button
type="button"
class="flex w-full items-center justify-between gap-2 border-b border-default px-3 py-3 text-left"
@click="collapsed = !collapsed"
>
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingSessionSummary.title') }}
</div>
<div class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingSessionSummary.pdfCount', { count: processSummary.total || displayOpenItems.length }) }}
</div>
</div>
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
</button>
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
<input
v-model="openOnlyFilter"
type="checkbox"
class="rounded border-default"
data-testid="shipping-session-open-only-filter"
/>
{{ t('chat.shippingSessionWorkItem.openOnlyFilter') }}
</label>
<div
v-if="handlingItems.length"
class="mb-3 space-y-1.5"
data-testid="shipping-session-handling-items"
>
<div class="text-[11px] font-medium text-secondary">
{{ t('chat.shippingOrderExtractionHandling.title') }}
</div>
<div
v-for="item in handlingItems"
:key="item.category"
class="rounded-md border border-default bg-surface-muted/60 px-2 py-1.5 text-xs"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="min-w-0 font-medium text-primary">
{{ handlingTitle(item.category) }}
<span class="ml-1 text-secondary">
{{ t('chat.shippingOrderExtractionHandling.count', { count: item.count }) }}
</span>
</div>
<button
type="button"
class="shrink-0 rounded-md border border-default px-2 py-0.5 text-[11px] font-medium text-primary hover:bg-surface"
@click="openHandlingAction(item.primary_action, item.affected_refs)"
>
{{ te(`chat.shippingOrderExtractionAction.${item.primary_action || 'view_details'}`)
? t(`chat.shippingOrderExtractionAction.${item.primary_action || 'view_details'}`)
: t('chat.shippingOrderExtractionAction.view_details') }}
</button>
</div>
<div
v-if="(item.reason_codes || []).length"
class="mt-1 text-[11px] text-secondary"
>
{{ t('chat.shippingOrderExtractionHandling.reasonPrefix') }}
{{ (item.reason_codes || []).slice(0, 4).map(handlingReasonLabel).join(';') }}
</div>
</div>
</div>
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingSessionSummary.completed', { count: processSummary.completed }) }}
</span>
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingSessionSummary.running', { count: processSummary.running }) }}
</span>
<span
v-if="processSummary.needsHuman > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingSessionSummary.needsHuman', { count: processSummary.needsHuman }) }}
</span>
<span
v-if="processSummary.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingSessionSummary.failed', { count: processSummary.failed }) }}
</span>
</div>
<div v-if="!displayOpenItems.length && !closedItems.length" class="text-xs text-muted">
{{ workItemsLoading
? t('chat.shippingSessionWorkItem.loading')
: t('chat.shippingSessionSummary.empty') }}
</div>
<ul v-if="displayOpenItems.length" class="space-y-2" data-testid="shipping-session-open-items">
<li
v-for="item in displayOpenItems"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-session-work-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div class="truncate text-xs font-semibold text-primary">
{{ item.current_document_filename || t('chat.shippingSessionSummary.unnamedPdf') }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingSessionWorkItem.versionLabel', { version: item.current_version_no }) }}
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
item.lifecycle_status === 'pending_review' || item.lifecycle_status === 'reparse_failed',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
item.lifecycle_status === 'extracting',
}"
>
{{ lifecycleStatusLabel(String(item.lifecycle_status || '')) }}
</span>
</div>
<div v-if="item.version_replaced" class="mt-1 text-[11px] text-secondary">
{{ t('chat.shippingSessionWorkItem.versionReplaced') }}
</div>
<div v-if="item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.updated_at) }}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<button
v-if="itemHasAction(item, 'enter_manual_review') && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-session-action-review"
@click="openManualReview(item)"
>
<ExternalLink class="h-3 w-3" />
{{ t('chat.shippingSessionWorkItem.enterManualReview') }}
</button>
<button
v-if="itemHasAction(item, 'request_reparse') && item.current_case_no"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-session-action-reparse"
@click="reparseFromPanel(item)"
>
{{ t('chat.shippingSessionWorkItem.requestReparse') }}
</button>
<button
v-if="itemHasAction(item, 'mark_non_order') && item.current_case_no"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-session-action-non-order"
@click="markNonOrderFromPanel(item)"
>
{{ t('chat.shippingSessionWorkItem.markNonOrder') }}
</button>
<button
v-if="itemHasAction(item, 'replace_file') && item.current_run_no"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-session-action-replace"
@click="replaceFileFromPanel(item)"
>
{{ t('chat.shippingSessionWorkItem.replaceFile') }}
</button>
<button
v-if="itemHasAction(item, 'cancel')"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-session-action-cancel"
@click="cancelWorkItem(item)"
>
{{ t('chat.shippingSessionWorkItem.cancelProcessing') }}
</button>
<button
v-if="itemHasAction(item, 'view_version_history')"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-session-action-versions"
@click="openVersionHistory(item)"
>
{{ t('chat.shippingSessionWorkItem.viewVersionHistory') }}
</button>
</div>
<div
v-if="versionHistoryItemNo === item.item_no"
class="mt-2 rounded-md border border-default bg-surface-muted/40 p-2"
data-testid="shipping-session-version-history"
>
<div class="text-[11px] font-medium text-secondary">
{{ t('chat.shippingSessionWorkItem.versionHistoryTitle') }}
</div>
<div v-if="versionHistoryLoading" class="mt-1 text-[11px] text-muted">
{{ t('chat.shippingSessionWorkItem.loading') }}
</div>
<ul v-else-if="versionHistoryItems.length" class="mt-1 space-y-1">
<li
v-for="version in versionHistoryItems"
:key="version.case_no"
class="text-[11px] text-primary"
>
{{ version.version_label || version.case_no }}
<span v-if="version.is_current" class="ml-1 text-brand-700">
({{ t('chat.shippingSessionWorkItem.currentVersion') }})
</span>
<span v-else-if="version.is_readonly" class="ml-1 text-muted">
({{ t('chat.shippingSessionWorkItem.readonlyVersion') }})
</span>
</li>
</ul>
<div v-else class="mt-1 text-[11px] text-muted">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
</div>
</div>
</li>
</ul>
<div
v-if="closedItems.length"
class="mt-3"
data-testid="shipping-session-closed-section"
>
<button
type="button"
class="flex w-full items-center justify-between gap-2 rounded-md border border-default bg-surface-muted/50 px-2 py-1.5 text-left text-[11px] font-medium text-secondary hover:bg-surface"
@click="closedExpanded = !closedExpanded"
>
<span>{{ t('chat.shippingSessionWorkItem.completedCollapsed', { count: closedItems.length }) }}</span>
<ChevronDown v-if="closedExpanded" class="h-3.5 w-3.5 shrink-0" />
<ChevronRight v-else class="h-3.5 w-3.5 shrink-0" />
</button>
<ul v-if="closedExpanded" class="mt-2 space-y-2">
<li
v-for="item in closedItems"
:key="`closed:${item.item_no}`"
class="rounded-lg border border-default bg-surface-soft/60 px-2.5 py-2 opacity-80"
>
<div class="truncate text-xs font-semibold text-primary">
{{ item.current_document_filename || t('chat.shippingSessionSummary.unnamedPdf') }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingSessionWorkItem.versionLabel', { version: item.current_version_no }) }}
<span v-if="item.closed_reason" class="ml-1">
· {{ closedReasonLabel(item.closed_reason) }}
</span>
</div>
</li>
</ul>
</div>
</div>
</aside>
</template>
@@ -2,7 +2,8 @@
* features/chat/components/messages/ShippingMatchResultCard.vue
* 用途:出货 Agent 对话区与工作台共用的库存匹配/缺口结果卡片。
* 依赖:shipping.api.types、vue-i18n。
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示状态、缺口与操作按钮。
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示;
* line_status 含 ok/partial/shortage/conflict(含 multi_file_conflict 别名),经 i18n rowStatus 映射。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
@@ -33,6 +34,9 @@ const rowStatusLabel = (status?: string | null) => {
if (status === 'ok') return t('chat.shippingNoticeUi.rowStatus.ok');
if (status === 'partial') return t('chat.shippingNoticeUi.rowStatus.partial');
if (status === 'shortage') return t('chat.shippingNoticeUi.rowStatus.shortage');
if (status === 'conflict' || status === 'multi_file_conflict') {
return t('chat.shippingNoticeUi.rowStatus.conflict');
}
return status || '-';
};
@@ -0,0 +1,167 @@
<!--
features/chat/components/shipping-review/ReviewBuildEligibilityPanel.vue
用途:展示建单前资格摘要(can_build、阻断原因、行级 Reservation 与库存候选)。
依赖:vue-i18n、ShippingOrderReviewBuildEligibility 类型。
逻辑:ShippingOrderReviewView 传入 draft.build_eligibility;只读展示,不发起写请求。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibility } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
eligibility: ShippingOrderReviewBuildEligibility | null;
}>();
const { t, te } = useI18n();
/**
* 解析建单资格状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingOrderReview.buildEligibility.status.${status}`;
return te(key) ? t(key) : status;
}
/**
* 解析行级阻断原因文案。
*/
function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 解析路由状态文案。
*/
function routingStatusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '—';
const key = `chat.shippingOrderReview.buildEligibility.routingStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/** 未满足建单资格的明细行。 */
const blockedLines = computed(() =>
(props.eligibility?.line_projections || []).filter((line) => line.can_build === false),
);
/** 阻断摘要:按 block_reason 聚合行数。 */
const blockingSummary = computed(() => {
const counts = new Map<string, number>();
for (const line of blockedLines.value) {
const reason = String(line.block_reason || 'unknown').trim() || 'unknown';
counts.set(reason, (counts.get(reason) || 0) + 1);
}
return [...counts.entries()].map(([reason, count]) => ({ reason, count }));
});
</script>
<template>
<section
v-if="eligibility"
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-build-eligibility-panel"
>
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.buildEligibility.subtitle') }}
</p>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-medium"
:class="eligibility.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
data-testid="review-build-eligibility-badge"
>
{{
eligibility.can_build
? t('chat.shippingOrderReview.buildEligibility.canBuildYes')
: t('chat.shippingOrderReview.buildEligibility.canBuildNo')
}}
</span>
</header>
<dl class="grid gap-2 text-xs text-slate-600 dark:text-slate-400 sm:grid-cols-2">
<div>
<dt class="inline font-medium">{{ t('chat.shippingOrderReview.buildEligibility.statusLabel') }}:</dt>
<dd class="inline">{{ statusLabel(eligibility.status) }}</dd>
</div>
</dl>
<div
v-if="!eligibility.can_build && blockingSummary.length"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 p-3 text-xs text-amber-950 dark:border-amber-900 dark:bg-amber-950/30 dark:text-amber-100"
data-testid="review-build-eligibility-blocking-summary"
>
<div class="font-semibold">{{ t('chat.shippingOrderReview.buildEligibility.blockingSummary') }}</div>
<ul class="mt-1 list-disc space-y-0.5 pl-4">
<li v-for="item in blockingSummary" :key="item.reason">
{{ blockReasonLabel(item.reason) }}
<span class="text-amber-800 dark:text-amber-200">× {{ item.count }}</span>
</li>
</ul>
</div>
<div v-if="eligibility.line_projections.length" class="mt-3 space-y-2">
<div class="text-xs font-semibold text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.buildEligibility.lineProjections') }}
</div>
<article
v-for="line in eligibility.line_projections"
:key="String(line.line_key || line.line_index)"
class="rounded-lg border border-slate-200 p-3 text-xs dark:border-slate-700"
:data-testid="`review-build-eligibility-line-${line.line_key || line.line_index}`"
>
<div class="flex flex-wrap items-center justify-between gap-2">
<span class="font-medium">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
</span>
<span
class="rounded-full px-2 py-0.5 text-[11px]"
:class="line.can_build
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
: 'bg-rose-100 text-rose-800 dark:bg-rose-950 dark:text-rose-100'"
>
{{
line.can_build
? t('chat.shippingOrderReview.buildEligibility.lineCanBuild')
: t('chat.shippingOrderReview.buildEligibility.lineBlocked')
}}
</span>
</div>
<dl class="mt-2 grid gap-1 sm:grid-cols-2">
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.reservation') }}:</dt>
<dd class="inline font-mono">{{ line.effective_reservation_id || '—' }}</dd>
</div>
<div>
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.routingStatusLabel') }}:</dt>
<dd class="inline">{{ routingStatusLabel(line.routing_status) }}</dd>
</div>
<div v-if="line.inventory_source_hint" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.sourceHint') }}:</dt>
<dd class="inline">{{ line.inventory_source_hint }}</dd>
</div>
<div v-if="line.candidate_inventory_source_codes?.length" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.candidates') }}:</dt>
<dd class="inline font-mono">{{ line.candidate_inventory_source_codes.join(', ') }}</dd>
</div>
<div v-if="line.block_reason" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.blockReason') }}:</dt>
<dd class="inline">{{ blockReasonLabel(line.block_reason) }}</dd>
</div>
<div v-if="line.selection_mode === 'manual' && line.manual_reason" class="sm:col-span-2">
<dt class="inline text-slate-500">{{ t('chat.shippingOrderReview.buildEligibility.manualReason') }}:</dt>
<dd class="inline">{{ line.manual_reason }}</dd>
</div>
</dl>
</article>
</div>
</section>
</template>
@@ -0,0 +1,176 @@
<!--
features/chat/components/shipping-review/ReviewInventoryCandidatesPanel.vue
用途:为库存路由未决的明细行提供多选候选源与强制原因的人工提交表单。
依赖:vue-i18n、ShippingOrderReviewBuildEligibilityLineProjection 类型。
逻辑:规则候选优先;零候选时回退到已启用库存源列表;emit submit 由 composable 写 API。
-->
<script setup lang="ts">
import { reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingOrderReviewBuildEligibilityLineProjection } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
lines: ShippingOrderReviewBuildEligibilityLineProjection[];
/** 已启用库存源;规则零候选时作为可选列表 */
enabledSourceCodes?: string[];
editable?: boolean;
saving?: boolean;
}>();
const emit = defineEmits<{
(e: 'submit', payload: { lineKey: string; sourceCodes: string[]; reason: string }): void;
}>();
const { t, te } = useI18n();
/** 每行本地表单状态:已选候选与原因。 */
const formState = reactive<Record<string, { selected: string[]; reason: string }>>({});
/**
* 行级可选源:规则候选优先,否则回退已启用库存源。
*/
function selectableCodes(line: ShippingOrderReviewBuildEligibilityLineProjection): string[] {
const candidates = (line.candidate_inventory_source_codes || [])
.map((code) => String(code || '').trim().toUpperCase())
.filter(Boolean);
if (candidates.length) return candidates;
return (props.enabledSourceCodes || [])
.map((code) => String(code || '').trim().toUpperCase())
.filter(Boolean);
}
/**
* 获取或初始化某行的表单状态。
*/
function getForm(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const key = String(line.line_key || (line.line_index ?? ''));
if (!formState[key]) {
const ruleCandidates = (line.candidate_inventory_source_codes || []).map(String);
formState[key] = {
selected: [...ruleCandidates],
reason: String(line.manual_reason || ''),
};
}
return formState[key];
}
/**
* 切换候选编码勾选状态。
*/
function toggleCode(line: ShippingOrderReviewBuildEligibilityLineProjection, code: string) {
const form = getForm(line);
const index = form.selected.indexOf(code);
if (index >= 0) form.selected.splice(index, 1);
else form.selected.push(code);
}
/**
* 解析阻断原因展示文案。
*/
function blockReasonLabel(reason?: string | null): string {
const normalized = String(reason || '').trim();
if (!normalized) return '';
const key = `chat.shippingOrderReview.buildEligibility.blockReasons.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 校验并提交指定行的人工候选选择。
*/
function submitLine(line: ShippingOrderReviewBuildEligibilityLineProjection) {
const lineKey = String(line.line_key || '').trim();
if (!lineKey) return;
const form = getForm(line);
emit('submit', {
lineKey,
sourceCodes: [...form.selected],
reason: form.reason.trim(),
});
}
</script>
<template>
<section
v-if="lines.length"
class="rounded-xl border border-sky-200 bg-sky-50/60 p-4 shadow-sm dark:border-sky-900 dark:bg-sky-950/20"
data-testid="review-inventory-candidates-panel"
>
<header class="mb-3">
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.inventoryCandidates.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-600 dark:text-slate-400">
{{ t('chat.shippingOrderReview.inventoryCandidates.subtitle') }}
</p>
</header>
<article
v-for="line in lines"
:key="String(line.line_key || line.line_index)"
class="mb-3 rounded-lg border border-slate-200 bg-white p-3 last:mb-0 dark:border-slate-700 dark:bg-slate-900"
:data-testid="`review-inventory-candidates-line-${line.line_key || line.line_index}`"
>
<div class="flex flex-wrap items-center justify-between gap-2 text-sm">
<span class="font-medium">
{{ t('chat.shippingOrderReview.line', { index: (line.line_index ?? 0) + 1 }) }}
<span v-if="line.effective_reservation_id" class="ml-1 font-mono text-xs text-slate-500">
{{ line.effective_reservation_id }}
</span>
</span>
<span v-if="line.block_reason" class="text-xs text-amber-800 dark:text-amber-200">
{{ blockReasonLabel(line.block_reason) }}
</span>
</div>
<div v-if="selectableCodes(line).length" class="mt-3">
<div class="text-xs font-medium text-slate-600 dark:text-slate-300">
{{
(line.candidate_inventory_source_codes || []).length
? t('chat.shippingOrderReview.inventoryCandidates.selectSources')
: t('chat.shippingOrderReview.inventoryCandidates.selectEnabledSources')
}}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<label
v-for="code in selectableCodes(line)"
:key="code"
class="inline-flex cursor-pointer items-center gap-1.5 rounded border border-slate-200 px-2 py-1 text-xs dark:border-slate-600"
>
<input
type="checkbox"
:checked="getForm(line).selected.includes(code)"
:disabled="!editable || saving"
@change="toggleCode(line, code)"
>
<span class="font-mono">{{ code }}</span>
</label>
</div>
</div>
<p v-else class="mt-2 text-xs text-rose-600 dark:text-rose-300">
{{ t('chat.shippingOrderReview.inventoryCandidates.noEnabledSources') }}
</p>
<label class="mt-3 block text-xs font-medium text-slate-600 dark:text-slate-300">
{{ t('chat.shippingOrderReview.inventoryCandidates.reasonLabel') }}
<textarea
:value="getForm(line).reason"
:disabled="!editable || saving"
rows="2"
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2 py-1.5 text-xs dark:border-slate-600 dark:bg-slate-950"
:placeholder="t('chat.shippingOrderReview.inventoryCandidates.reasonPlaceholder')"
@input="getForm(line).reason = ($event.target as HTMLTextAreaElement).value"
/>
</label>
<div class="mt-3 flex justify-end">
<button
type="button"
class="rounded bg-sky-600 px-3 py-1.5 text-xs text-white disabled:opacity-50"
data-testid="review-inventory-candidates-submit"
:disabled="!editable || saving || !getForm(line).selected.length || !getForm(line).reason.trim()"
@click="submitLine(line)"
>
{{ t('chat.shippingOrderReview.inventoryCandidates.submit') }}
</button>
</div>
</article>
</section>
</template>
@@ -0,0 +1,259 @@
<!--
features/chat/components/shipping-review/ReviewLineNoOverrideDialog.vue
用途:复核页编辑内部项次 line_no 时的强制原因弹窗(覆盖须审计)。
依赖:vue-i18n、dialog-overlay / dialog-panel。
逻辑:ShippingOrderReviewView 拦截 line_no 输入变更;确认后携带 reasonCode/reasonText 调用 patchLine。
确认仅发出事件,不自行关闭;父组件成功后再关,失败时保留原因选择与说明。
打开时聚焦原因选择框,Tab 焦点陷阱在弹窗内,关闭后恢复先前焦点。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
/** 与后端 LINE_NO_OVERRIDE_REASON_CODES 对齐的稳定原因码。 */
const LINE_NO_OVERRIDE_REASON_CODES = [
'recognition_error',
'customer_line_exception',
'business_correction',
'other',
] as const;
type LineNoOverrideReasonCode = (typeof LINE_NO_OVERRIDE_REASON_CODES)[number];
/** 内部项次覆盖确认载荷;供复核页 confirm 事件消费。 */
export type LineNoOverridePayload = {
value: string;
reasonCode: LineNoOverrideReasonCode;
reasonText: string;
};
interface Props {
modelValue: boolean;
/** 用户拟写入的新项次值(已在输入框中编辑)。 */
pendingValue: string;
confirmLoading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
confirmLoading: false,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm', payload: LineNoOverridePayload): void;
(e: 'cancel'): void;
}>();
const { t } = useI18n();
const reasonCode = ref<LineNoOverrideReasonCode>('recognition_error');
const reasonText = ref('');
const reasonMissing = ref(false);
const textMissing = ref(false);
const panelRef = ref<HTMLElement | null>(null);
const reasonSelectRef = ref<HTMLSelectElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const title = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.title'));
const impact = computed(() => t('chat.shippingOrderReview.lineNoOverrideDialog.impact'));
/**
* 原因码展示文案。
* @param code - 后端允许的覆盖原因码
*/
const reasonLabel = (code: string) =>
t(`chat.shippingOrderReview.lineNoOverrideDialog.reasons.${code}`);
/** 收集弹窗内可聚焦控件,供 Tab 陷阱使用。 */
const focusableNodes = (): HTMLElement[] => {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
};
/** 关闭弹窗并同步 v-model。 */
const closeDialog = () => {
emit('update:modelValue', false);
};
const handleCancel = () => {
if (props.confirmLoading) return;
emit('cancel');
closeDialog();
};
/**
* 校验原因码与「其他」说明后提交覆盖。
* 核心逻辑:other 强制补充说明;确认后不关闭,由父组件在保存成功后再关,失败时保留表单。
*/
const handleConfirm = () => {
if (props.confirmLoading) return;
reasonMissing.value = false;
textMissing.value = false;
if (!reasonCode.value) {
reasonMissing.value = true;
return;
}
const trimmed = reasonText.value.trim();
if (reasonCode.value === 'other' && !trimmed) {
textMissing.value = true;
return;
}
emit('confirm', {
value: String(props.pendingValue ?? '').trim(),
reasonCode: reasonCode.value,
reasonText: trimmed,
});
};
/**
* Escape 关闭;Tab / Shift+Tab 在弹窗内循环,阻止焦点逃逸到背景页。
*/
const onKeydown = (event: KeyboardEvent) => {
if (!props.modelValue) return;
if (event.key === 'Escape' && !props.confirmLoading) {
event.preventDefault();
event.stopPropagation();
handleCancel();
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
};
watch(
() => props.modelValue,
async (open, wasOpen) => {
if (typeof document === 'undefined') return;
if (open && !wasOpen) {
reasonCode.value = 'recognition_error';
reasonText.value = '';
reasonMissing.value = false;
textMissing.value = false;
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
(reasonSelectRef.value || focusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="modelValue"
class="dialog-overlay z-50 flex items-center justify-center p-4"
role="dialog"
aria-modal="true"
:aria-label="title"
data-testid="review-line-no-override-dialog"
@click.self="handleCancel"
>
<div ref="panelRef" class="dialog-panel w-full max-w-md space-y-4 p-5">
<header>
<h2 class="text-base font-semibold text-primary" id="review-line-no-override-title">{{ title }}</h2>
<p class="mt-2 text-sm text-secondary">{{ impact }}</p>
<p class="mt-2 text-sm text-primary">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.newValue', { value: pendingValue || '—' }) }}
</p>
</header>
<label class="block space-y-1 text-sm">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeLabel') }}</span>
<select
ref="reasonSelectRef"
v-model="reasonCode"
class="select-field w-full text-sm"
data-testid="review-line-no-reason-code"
:disabled="confirmLoading"
:aria-labelledby="'review-line-no-override-title'"
@change="reasonMissing = false"
>
<option v-for="code in LINE_NO_OVERRIDE_REASON_CODES" :key="code" :value="code">
{{ reasonLabel(code) }}
</option>
</select>
<p v-if="reasonMissing" class="text-xs text-rose-600 dark:text-rose-400">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonCodeRequired') }}
</p>
</label>
<label class="block space-y-1 text-sm">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextLabel') }}</span>
<textarea
v-model="reasonText"
rows="3"
class="input-field w-full resize-y text-sm"
:placeholder="t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextPlaceholder')"
data-testid="review-line-no-reason-text"
:disabled="confirmLoading"
@input="textMissing = false"
/>
<p v-if="textMissing" class="text-xs text-rose-600 dark:text-rose-400">
{{ t('chat.shippingOrderReview.lineNoOverrideDialog.reasonTextRequired') }}
</p>
</label>
<footer class="flex justify-end gap-2 pt-1">
<button type="button" class="btn-secondary btn-sm" :disabled="confirmLoading" @click="handleCancel">
{{ t('common.deleteDialog.cancel') }}
</button>
<button
type="button"
class="btn-primary btn-sm"
:disabled="confirmLoading"
data-testid="review-line-no-override-submit"
@click="handleConfirm"
>
{{ confirmLoading ? t('chat.shippingOrderReview.saving') : t('chat.shippingOrderReview.lineNoOverrideDialog.confirm') }}
</button>
</footer>
</div>
</div>
</Teleport>
</template>
@@ -1,16 +1,16 @@
<!--
features/chat/components/shipping-review/ReviewVersionHistoryPanel.vue
用途:复核页工作项版本历史时间线;支持只读跳转至历史 Case。
依赖:vue-i18n、ShippingSessionWorkItemVersion 类型。
逻辑:ShippingOrderReviewView 传入 versions;emit select 供父级切换 case_no。
用途:复核页 WorkflowItem 版本历史时间线;支持只读跳转至历史 Case。
依赖:vue-i18n、ShippingWorkflowItemVersion 类型。
逻辑:ShippingOrderReviewView 传入 versions(由 WorkflowItem 派生);emit select 供父级切换 case_no。
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingSessionWorkItemVersion } from '@/features/chat/types/shipping.api.types';
import type { ShippingWorkflowItemVersion } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
itemNo?: string | null;
versions: ShippingSessionWorkItemVersion[];
versions: ShippingWorkflowItemVersion[];
loading?: boolean;
activeCaseNo?: string | null;
}>();
@@ -43,7 +43,7 @@ function formatTime(value?: string | null): string {
/**
* 跳转至指定版本;历史版本以只读模式打开。
*/
function selectVersion(version: ShippingSessionWorkItemVersion) {
function selectVersion(version: ShippingWorkflowItemVersion) {
const caseNo = String(version.case_no || '').trim();
if (!caseNo) return;
emit('select', caseNo, Boolean(version.is_readonly));
@@ -65,12 +65,16 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
</div>
</header>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingSessionWorkItem.loading') }}</div>
<p v-else-if="!versions.length" class="py-4 text-sm text-slate-500">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
</p>
<div v-if="loading" class="py-4 text-sm text-slate-500">{{ t('chat.shippingWorkflow.loading') }}</div>
<template v-else>
<p class="mb-2 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingWorkflow.versionHistoryNote') }}
</p>
<p v-if="!versions.length" class="py-4 text-sm text-slate-500">
{{ t('chat.shippingSessionWorkItem.noVersions') }}
</p>
<ol v-else class="space-y-2">
<ol v-else class="space-y-2">
<li
v-for="version in versions"
:key="version.case_no"
@@ -84,7 +88,7 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium">
{{ version.version_label || t('chat.shippingSessionWorkItem.versionLabel', { version: '?' }) }}
{{ version.version_label || t('chat.shippingWorkflow.versionLabel', { version: version.version_no || '?' }) }}
</span>
<span
v-if="version.is_current"
@@ -100,7 +104,7 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
</span>
</div>
<p class="mt-1 truncate text-xs text-slate-500 dark:text-slate-400">
{{ version.document_filename || version.case_no }}
{{ version.run_no || version.case_no }}
</p>
</div>
<button
@@ -124,12 +128,9 @@ function selectVersion(version: ShippingSessionWorkItemVersion) {
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.createdAt') }}:</dt>
<dd class="inline">{{ formatTime(version.created_at) }}</dd>
</div>
<div v-if="version.confirmed_at">
<dt class="inline">{{ t('chat.shippingOrderReview.versionHistory.confirmedAt') }}:</dt>
<dd class="inline">{{ formatTime(version.confirmed_at) }}</dd>
</div>
</dl>
</li>
</ol>
</template>
</section>
</template>
@@ -0,0 +1,83 @@
/**
* features/chat/components/shipping-review/ReviewWorkflowProgressPanel.spec.ts
* 用途:确认后自动进度面板节点状态与无货代上传按钮契约。
* 依赖:vitest、@vue/test-utils、vue-i18n stub、RouterLink stub。
* 逻辑:按 lifecycle_status 断言 done/active/pending;待登记时展示下一步说明与任务处理台入口。
*/
import { describe, expect, it } from 'vitest';
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import ReviewWorkflowProgressPanel from './ReviewWorkflowProgressPanel.vue';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const messages = {
en: {
chat: {
shippingOrderReview: {
workflowProgress: {
title: 'Auto progress',
subtitle: 'Stops at waiting for manual upload registration',
polling: 'Refreshing…',
taskNo: 'Task {taskNo}',
openTaskWorkbench: 'Open task workbench to register',
noUploadHint: 'Register credentials in the task workbench',
nextStepsManualUpload:
'Next: download Excel → upload on freight platform → submit evidence and receipt',
nodes: {
building_order: 'Create task',
inventory_matching: 'Match inventory',
generating_excel: 'Generate Excel',
manual_upload_pending: 'Awaiting upload registration',
},
},
},
},
},
};
/**
* 挂载进度面板。
*/
function mountPanel(item: Partial<ShippingWorkflowItem> | null, extras?: { taskNo?: string; polling?: boolean }) {
const i18n = createI18n({ legacy: false, locale: 'en', messages });
return mount(ReviewWorkflowProgressPanel, {
props: {
item: item as ShippingWorkflowItem | null,
taskNo: extras?.taskNo ?? 'SN-1',
polling: extras?.polling ?? true,
},
global: {
plugins: [i18n],
stubs: {
RouterLink: {
props: ['to'],
template: '<a :href="JSON.stringify(to)"><slot /></a>',
},
},
},
});
}
describe('ReviewWorkflowProgressPanel', () => {
it('marks earlier nodes done and current active', () => {
const wrapper = mountPanel({ lifecycle_status: 'generating_excel', current_stage: 'generating_excel' });
expect(wrapper.get('[data-testid="review-workflow-progress-node-building_order"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-inventory_matching"]').attributes('data-state')).toBe('done');
expect(wrapper.get('[data-testid="review-workflow-progress-node-generating_excel"]').attributes('data-state')).toBe('active');
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('pending');
expect(wrapper.find('[data-testid="review-open-task-workbench"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-manual-upload-next-steps"]').exists()).toBe(false);
});
it('shows manual_upload_pending next steps and task workbench link', () => {
const wrapper = mountPanel({ lifecycle_status: 'manual_upload_pending' }, { polling: false });
expect(wrapper.get('[data-testid="review-workflow-progress-node-manual_upload_pending"]').attributes('data-state')).toBe('active');
expect(wrapper.get('[data-testid="review-manual-upload-next-steps"]').text()).toContain('download Excel');
const link = wrapper.get('[data-testid="review-open-task-workbench"]');
expect(link.text()).toContain('Open task workbench to register');
expect(link.attributes('href')).toContain('workspace-shipping-my-tasks');
expect(link.attributes('href')).toContain('SN-1');
expect(wrapper.find('[data-testid="review-upload-freight"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
});
});
@@ -0,0 +1,150 @@
<!--
features/chat/components/shipping-review/ReviewWorkflowProgressPanel.vue
用途:复核确认后展示自动进度节点:创建任务 → 库存匹配 → 生成 Excel → 待人工上传登记。
依赖:vue-i18n、vue-router、ShippingWorkflowItem。
逻辑:ShippingOrderReviewView 在确认后挂载;按 lifecycle_status / current_stage 点亮节点;
无货代上传按钮;待登记时说明下一步并提供跳转任务处理台入口;
轮询由父级 composable 负责。
-->
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { RouterLink } from 'vue-router';
import type { ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
item: ShippingWorkflowItem | null;
taskNo?: string | null;
polling?: boolean;
}>();
const { t } = useI18n();
/** 进度节点稳定键;与 WorkflowItem lifecycle 对齐。 */
type ReviewProgressNodeKey =
| 'building_order'
| 'inventory_matching'
| 'generating_excel'
| 'manual_upload_pending';
const NODES: ReviewProgressNodeKey[] = [
'building_order',
'inventory_matching',
'generating_excel',
'manual_upload_pending',
];
/**
* 将 Item 生命周期映射到进度节点索引(0..3);未知时按建单中。
*/
function nodeIndex(status?: string | null): number {
const normalized = String(status || '').trim();
const idx = NODES.indexOf(normalized as ReviewProgressNodeKey);
if (idx >= 0) return idx;
if (['closed', 'cancelled'].includes(normalized)) return NODES.length - 1;
if (['pending_review', 'queued', 'layout_parsing', 'extracting'].includes(normalized)) return -1;
return 0;
}
const activeIndex = computed(() =>
nodeIndex(props.item?.lifecycle_status || props.item?.current_stage),
);
const showTaskWorkbenchLink = computed(() => {
const status = String(props.item?.lifecycle_status || props.item?.current_stage || '').trim();
return status === 'manual_upload_pending' && Boolean(String(props.taskNo || '').trim());
});
/**
* 任务处理台路由:带 task_no,便于直接定位待登记任务。
*/
const taskWorkbenchTo = computed(() => ({
name: 'workspace-shipping-my-tasks',
query: {
task_no: String(props.taskNo || '').trim(),
},
}));
/**
* 节点展示态:done / active / pending。
*/
function nodeState(index: number): 'done' | 'active' | 'pending' {
const current = activeIndex.value;
if (current < 0) return 'pending';
if (index < current) return 'done';
if (index === current) return 'active';
return 'pending';
}
</script>
<template>
<section
class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900"
data-testid="review-workflow-progress-panel"
>
<header class="mb-3 flex flex-wrap items-center justify-between gap-2">
<div>
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.workflowProgress.title') }}</h2>
<p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
{{ t('chat.shippingOrderReview.workflowProgress.subtitle') }}
</p>
</div>
<span
v-if="polling"
class="text-xs text-sky-700 dark:text-sky-300"
data-testid="review-workflow-progress-polling"
>
{{ t('chat.shippingOrderReview.workflowProgress.polling') }}
</span>
</header>
<div
v-if="taskNo"
class="mb-3 flex flex-wrap items-center gap-2 text-xs text-slate-600 dark:text-slate-400"
>
<span>{{ t('chat.shippingOrderReview.workflowProgress.taskNo', { taskNo }) }}</span>
<RouterLink
v-if="showTaskWorkbenchLink"
:to="taskWorkbenchTo"
class="inline-flex items-center rounded-lg bg-brand-600 px-2.5 py-1 text-xs font-medium text-white hover:bg-brand-700"
data-testid="review-open-task-workbench"
>
{{ t('chat.shippingOrderReview.workflowProgress.openTaskWorkbench') }}
</RouterLink>
</div>
<ol class="space-y-2" data-testid="review-workflow-progress-nodes">
<li
v-for="(key, index) in NODES"
:key="key"
class="flex items-center gap-3 rounded-lg border px-3 py-2 text-sm"
:class="{
'border-emerald-200 bg-emerald-50 text-emerald-900 dark:border-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-100': nodeState(index) === 'done',
'border-sky-200 bg-sky-50 text-sky-950 dark:border-sky-900 dark:bg-sky-950/40 dark:text-sky-100': nodeState(index) === 'active',
'border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/40 dark:text-slate-400': nodeState(index) === 'pending',
}"
:data-testid="`review-workflow-progress-node-${key}`"
:data-state="nodeState(index)"
>
<span class="inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-xs font-semibold">
{{ index + 1 }}
</span>
<span>{{ t(`chat.shippingOrderReview.workflowProgress.nodes.${key}`) }}</span>
</li>
</ol>
<p
v-if="showTaskWorkbenchLink"
class="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-100"
data-testid="review-manual-upload-next-steps"
>
{{ t('chat.shippingOrderReview.workflowProgress.nextStepsManualUpload') }}
</p>
<p
v-else
class="mt-3 text-xs text-slate-500 dark:text-slate-400"
>
{{ t('chat.shippingOrderReview.workflowProgress.noUploadHint') }}
</p>
</section>
</template>
@@ -1,11 +1,12 @@
/**
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
* 用途:聊天主区批次进度卡——摘要计数、Run 级处理事项、当前文件阶段、健康提醒与动作。
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、vue-router、vue-i18n。
* 逻辑:事实一律来自后端 handling_items / primary_notice;右侧 ShippingSessionSummaryPanel 承接逐 PDF 明细。
* 依赖:订单抽取 Run 状态卡 DTO、orderExtractionProgressDisplay、Workflow 计数投影、vue-router、vue-i18n。
* 逻辑:有 Workflow 投影时优先展示统一 counts;否则回退 handling_items / primary_notice;
* 右侧 ShippingWorkflowTimeline 承接逐 PDF 明细;禁止发明百分比与 ETA。
*/
<script setup lang="ts">
import { computed, ref } from 'vue';
import { computed, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
@@ -13,6 +14,7 @@ import type {
ShippingOrderExtractionHandlingItemState,
ShippingOrderExtractionState,
} from '../../types/chat.types';
import type { ShippingWorkflowItemCounts } from '../../types/shipping.api.types';
import {
formatOrderExtractionElapsed,
resolveOrderExtractionUserStageKey,
@@ -22,6 +24,7 @@ import {
type ShippingHandlingAffectedRef,
type ShippingHandlingRefTarget,
} from '../../shipping/orderExtractionHandlingRefs';
import { SHIPPING_WORKFLOW_KEY } from '../../shipping/useShippingNoticeWorkflow';
const props = defineProps<{
state: ShippingOrderExtractionState;
@@ -29,6 +32,8 @@ const props = defineProps<{
retrying?: boolean;
refreshing?: boolean;
cancelling?: boolean;
/** 可选:父级传入的 Workflow 计数;优先于 Run summary。 */
workflowSummary?: ShippingWorkflowItemCounts | null;
}>();
const emit = defineEmits<{
@@ -42,6 +47,49 @@ const route = useRoute();
const router = useRouter();
const confirmCancelOpen = ref(false);
const cancelReason = ref('');
const injectedWorkflow = inject(SHIPPING_WORKFLOW_KEY, null);
/**
* 统一计数:优先 props.workflowSummary,其次 inject 的 Workflow.counts,最后回退 Run summary。
*/
const unifiedCounts = computed(() => {
const fromProp = props.workflowSummary;
if (fromProp && Number(fromProp.total || 0) > 0) return fromProp;
const fromInject = injectedWorkflow?.workflow.value?.counts;
if (fromInject && Number(fromInject.total || 0) > 0) return fromInject;
return null;
});
const displaySummary = computed(() => {
const counts = unifiedCounts.value;
if (!counts) return props.state.summary;
return {
totalDocuments: counts.total,
processingDocuments: counts.processing,
pendingDocuments: 0,
completedDocuments: counts.completed,
reviewRequiredDocuments: counts.pending_review,
failedDocuments: counts.failed,
cancelledDocuments: 0,
candidateCount: props.state.summary.candidateCount,
openedExistingCount: props.state.summary.openedExistingCount,
};
});
const workflowStageLabel = computed(() => {
const stage = String(injectedWorkflow?.workflow.value?.current_stage || '').trim();
if (!stage) return '';
const key = `chat.shippingWorkflow.itemStatus.${stage}`;
return te(key) ? t(key) : stage;
});
const workflowLastActivityLabel = computed(() => {
const raw = injectedWorkflow?.workflow.value?.last_activity_at;
if (!raw) return '';
const date = new Date(String(raw));
if (Number.isNaN(date.getTime())) return '';
return date.toLocaleString();
});
const handlingItems = computed(() => props.state.handlingItems || []);
@@ -50,10 +98,10 @@ const handlingItems = computed(() => props.state.handlingItems || []);
*/
const isDuplicateOnlyNotice = computed(() => {
if (handlingItems.value.length > 0) return false;
const opened = Math.max(0, Number(props.state.summary.openedExistingCount || 0));
const opened = Math.max(0, Number(displaySummary.value.openedExistingCount || 0));
if (opened <= 0) return false;
const review = Math.max(0, Number(props.state.summary.reviewRequiredDocuments || 0));
const failed = Math.max(0, Number(props.state.summary.failedDocuments || 0));
const review = Math.max(0, Number(displaySummary.value.reviewRequiredDocuments || 0));
const failed = Math.max(0, Number(displaySummary.value.failedDocuments || 0));
return review === 0 && failed === 0;
});
@@ -163,7 +211,7 @@ const activityKey = computed(() => {
const showRetry = computed(() => (
props.state.availableActions.includes('retry_failed_attachments')
|| props.state.summary.failedDocuments > 0
|| displaySummary.value.failedDocuments > 0
));
const showRefresh = computed(() => props.state.availableActions.includes('refresh_status'));
const showCancel = computed(() => (
@@ -319,31 +367,40 @@ function openCancelConfirm() {
<div class="text-sm font-medium">{{ compactLine }}</div>
<div
v-if="state.summary.totalDocuments > 0"
v-if="displaySummary.totalDocuments > 0"
class="mt-1.5 flex flex-wrap gap-1.5 text-[11px] opacity-90"
data-testid="shipping-order-extraction-summary"
>
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
<span v-if="state.summary.processingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.processing', { count: state.summary.processingDocuments }) }}
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: displaySummary.totalDocuments }) }}</span>
<span v-if="displaySummary.processingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.processing', { count: displaySummary.processingDocuments }) }}
</span>
<span v-if="state.summary.pendingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.pending', { count: state.summary.pendingDocuments }) }}
<span v-if="displaySummary.pendingDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.pending', { count: displaySummary.pendingDocuments }) }}
</span>
<span v-if="state.summary.completedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.completed', { count: state.summary.completedDocuments }) }}
<span v-if="displaySummary.completedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.completed', { count: displaySummary.completedDocuments }) }}
</span>
<span v-if="state.summary.reviewRequiredDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}
<span v-if="displaySummary.reviewRequiredDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: displaySummary.reviewRequiredDocuments }) }}
</span>
<span v-if="state.summary.failedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
<span v-if="displaySummary.failedDocuments > 0">
{{ t('chat.shippingOrderExtractionSummary.failed', { count: displaySummary.failedDocuments }) }}
</span>
<span v-if="(state.summary.cancelledDocuments || 0) > 0">
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: state.summary.cancelledDocuments }) }}
<span v-if="(displaySummary.cancelledDocuments || 0) > 0">
{{ t('chat.shippingOrderExtractionSummary.cancelled', { count: displaySummary.cancelledDocuments }) }}
</span>
</div>
<div
v-if="workflowStageLabel || workflowLastActivityLabel"
class="mt-1 text-[11px] opacity-80"
data-testid="shipping-order-extraction-workflow-meta"
>
<span v-if="workflowStageLabel">{{ workflowStageLabel }}</span>
<span v-if="workflowLastActivityLabel" class="ml-1">· {{ workflowLastActivityLabel }}</span>
</div>
<div
v-if="handlingItems.length"
class="mt-2 space-y-1.5"
@@ -0,0 +1,113 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.spec.ts
* 用途:覆盖单个 WorkflowItem 详情抽屉的文件名/阶段/事件展示与取消/重识别入口。
* 依赖:Vitest、Vue Test Utils、vue-i18n。
* 逻辑:断言打开时展示 filename 与事件;终态隐藏取消;emit close/cancel/reparse。
* Teleport 到 body 后通过 document.querySelector 读取抽屉根节点。
*/
import { mount } from '@vue/test-utils';
import { afterEach, describe, expect, it } from 'vitest';
import { createI18n } from 'vue-i18n';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import type { ShippingWorkflowItem } from '../../types/shipping.api.types';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-DETAIL',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'order-detail.pdf',
current_version_no: 2,
current_run_no: 'SNER-9',
lifecycle_status: 'extracting',
current_stage: 'extracting',
lock_version: 1,
events: [
{
seq_no: 1,
event_code: 'item_created',
actor_type: 'system',
occurred_at: '2026-07-30T10:00:00Z',
},
],
...patch,
};
}
/** Teleport 后从 document 取抽屉根节点。 */
function drawerRoot(): HTMLElement | null {
return document.querySelector('[data-testid="shipping-workflow-item-drawer"]');
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('ShippingWorkflowItemDetailDrawer', () => {
it('renders filename, stage and events when open', () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: { open: true, item: buildItem() },
global: { plugins: [i18n] },
attachTo: document.body,
});
const root = drawerRoot();
expect(root).not.toBeNull();
expect(root?.getAttribute('role')).toBe('dialog');
expect(root?.getAttribute('aria-modal')).toBe('true');
expect(root?.textContent).toContain('order-detail.pdf');
expect(root?.textContent).toContain('SNER-9');
expect(root?.querySelector('[data-testid="shipping-workflow-item-events"]')).not.toBeNull();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).not.toBeNull();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-reparse"]')).toBeNull();
wrapper.unmount();
});
it('shows reparse for failed items and emits reparse', async () => {
const wrapper = mount(ShippingWorkflowItemDetailDrawer, {
props: {
open: true,
item: buildItem({ lifecycle_status: 'failed', current_document_filename: 'fail.pdf' }),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const reparseBtn = drawerRoot()?.querySelector(
'[data-testid="shipping-workflow-item-drawer-reparse"]',
) as HTMLButtonElement | null;
expect(reparseBtn).not.toBeNull();
reparseBtn?.click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('reparse')?.[0]?.[0]).toMatchObject({ item_no: 'SWI-DETAIL' });
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' }),
},
global: { plugins: [i18n] },
attachTo: document.body,
});
const root = drawerRoot();
expect(root?.querySelector('[data-testid="shipping-workflow-item-drawer-cancel"]')).toBeNull();
const closeBtn = root?.querySelector(
'[data-testid="shipping-workflow-item-drawer-close"]',
) as HTMLButtonElement | null;
expect(closeBtn).not.toBeNull();
closeBtn?.click();
await wrapper.vm.$nextTick();
expect(wrapper.emitted('close')).toBeTruthy();
wrapper.unmount();
});
});
@@ -0,0 +1,312 @@
/**
* features/chat/components/shipping/ShippingWorkflowItemDetailDrawer.vue
* 用途:单个 WorkflowItem(PDF)详情抽屉——文件名、阶段、事件时间线、取消/重识别入口。
* 依赖:vue-i18n、ShippingWorkflowItem / Event 类型、lucide-vue-next。
* 逻辑:由 ShippingWorkflowTimeline 打开;展示 filename / current_stage / events;
* 取消与重识别仅 emit,由父级用应用内原因弹窗收集;禁止发明百分比与 ETA。
* 以模态对话框语义呈现:初始焦点、Tab 陷阱、Escape/关闭后焦点恢复。
*/
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { X } from 'lucide-vue-next';
import type { ShippingWorkflowEvent, ShippingWorkflowItem } from '@/features/chat/types/shipping.api.types';
const props = defineProps<{
open: boolean;
item: ShippingWorkflowItem | null;
loading?: boolean;
cancelling?: boolean;
reparsing?: boolean;
}>();
const emit = defineEmits<{
close: [];
cancel: [item: ShippingWorkflowItem];
reparse: [item: ShippingWorkflowItem];
}>();
const { t, te, locale } = useI18n();
const panelRef = ref<HTMLElement | null>(null);
const closeButtonRef = ref<HTMLButtonElement | null>(null);
let previouslyFocused: HTMLElement | null = null;
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'textarea:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const events = computed((): ShippingWorkflowEvent[] => (
Array.isArray(props.item?.events) ? props.item!.events! : []
));
const canCancel = computed(() => {
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && !['closed', 'cancelled'].includes(status);
});
const canReparse = computed(() => {
const status = String(props.item?.lifecycle_status || '').trim();
return Boolean(props.item) && ['failed', 'reparse_failed', 'pending_review'].includes(status);
});
const filename = computed(() => {
const name = String(props.item?.current_document_filename || '').trim();
if (name) return name;
if (!props.item) return '';
return t('chat.shippingWorkflow.filenameFallback', {
docId: props.item.current_document_id,
});
});
const title = computed(() => t('chat.shippingWorkflow.detail.title'));
/**
* 解析生命周期 / 阶段文案。
*/
function statusLabel(status?: string | null): string {
const normalized = String(status || '').trim();
if (!normalized) return '';
const key = `chat.shippingWorkflow.itemStatus.${normalized}`;
return te(key) ? t(key) : normalized;
}
/**
* 解析事件码文案。
*/
function eventLabel(event: ShippingWorkflowEvent): string {
const code = String(event.message_code || event.event_code || '').trim();
if (!code) return '—';
const key = `chat.shippingWorkflow.event.${code}`;
return te(key) ? t(key) : code;
}
/**
* 格式化时间为本地短时间。
*/
function formatTime(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
}
/** 收集抽屉内可聚焦控件。 */
function focusableNodes(): HTMLElement[] {
if (!panelRef.value) return [];
return Array.from(panelRef.value.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR))
.filter((node) => !node.hasAttribute('disabled') && node.getAttribute('aria-hidden') !== 'true');
}
/** 关闭抽屉。 */
function handleClose(): void {
emit('close');
}
/**
* Escape 关闭;Tab 在抽屉内循环,阻止焦点逃逸到背景页。
*/
function onKeydown(event: KeyboardEvent): void {
if (!props.open) return;
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
handleClose();
return;
}
if (event.key !== 'Tab') return;
const nodes = focusableNodes();
const first = nodes[0];
const last = nodes[nodes.length - 1];
// noUncheckedIndexedAccess:空数组或下标越界时 first/last 可能为 undefined。
if (!first || !last) {
event.preventDefault();
return;
}
const active = document.activeElement as HTMLElement | null;
const inside = Boolean(active && panelRef.value?.contains(active));
if (event.shiftKey) {
if (!inside || active === first) {
event.preventDefault();
last.focus();
}
return;
}
if (!inside || active === last) {
event.preventDefault();
first.focus();
}
}
watch(
() => props.open,
async (open, wasOpen) => {
if (typeof document === 'undefined') return;
if (open && !wasOpen) {
previouslyFocused = document.activeElement instanceof HTMLElement
? document.activeElement
: null;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
(closeButtonRef.value || focusableNodes()[0])?.focus();
return;
}
if (!open && wasOpen) {
document.removeEventListener('keydown', onKeydown, true);
const restoreTarget = previouslyFocused;
previouslyFocused = null;
await nextTick();
restoreTarget?.focus?.();
}
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-40 flex justify-end bg-black/30"
role="dialog"
aria-modal="true"
aria-labelledby="shipping-workflow-item-drawer-title"
data-testid="shipping-workflow-item-drawer"
@click.self="handleClose"
>
<aside
ref="panelRef"
class="flex h-full w-full max-w-md flex-col border-l border-default bg-surface shadow-xl"
>
<header class="flex items-start justify-between gap-2 border-b border-default px-4 py-3">
<div class="min-w-0">
<h2 id="shipping-workflow-item-drawer-title" class="text-sm font-semibold text-primary">
{{ title }}
</h2>
<p
v-if="item"
class="mt-0.5 truncate text-xs text-secondary"
data-testid="shipping-workflow-item-drawer-filename"
>
{{ filename }}
· V{{ item.current_version_no }}
</p>
</div>
<button
ref="closeButtonRef"
type="button"
class="rounded-md p-1 text-muted hover:bg-surface-muted"
:aria-label="t('chat.shippingWorkflow.detail.close')"
data-testid="shipping-workflow-item-drawer-close"
@click="handleClose"
>
<X class="h-4 w-4" />
</button>
</header>
<div class="min-h-0 flex-1 overflow-auto p-4">
<div v-if="loading" class="text-xs text-muted">
{{ t('chat.shippingWorkflow.loading') }}
</div>
<template v-else-if="item">
<dl class="space-y-2 text-xs">
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.filename') }}</dt>
<dd class="max-w-[60%] truncate font-medium text-primary" :title="filename">{{ filename }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.status') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.lifecycle_status) }}</dd>
</div>
<div class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.stage') }}</dt>
<dd class="font-medium text-primary">{{ statusLabel(item.current_stage) || item.current_stage }}</dd>
</div>
<div v-if="item.current_run_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.runNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_run_no }}</dd>
</div>
<div v-if="item.current_case_no" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.caseNo') }}</dt>
<dd class="font-medium text-primary">{{ item.current_case_no }}</dd>
</div>
<div v-if="item.last_activity_at" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.lastActivity') }}</dt>
<dd class="font-medium text-primary">{{ formatTime(item.last_activity_at) }}</dd>
</div>
<div v-if="item.closed_reason" class="flex justify-between gap-2">
<dt class="text-secondary">{{ t('chat.shippingWorkflow.detail.closedReason') }}</dt>
<dd class="font-medium text-primary">
{{ te(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
? t(`chat.shippingWorkflow.closedReason.${item.closed_reason}`)
: item.closed_reason }}
</dd>
</div>
</dl>
<section class="mt-4">
<h3 class="text-xs font-semibold text-secondary">
{{ t('chat.shippingWorkflow.detail.eventsTitle') }}
</h3>
<ul v-if="events.length" class="mt-2 space-y-2" data-testid="shipping-workflow-item-events">
<li
v-for="event in events"
:key="`${event.seq_no}-${event.event_code}`"
class="rounded-md border border-default bg-surface-muted/40 px-2.5 py-2 text-xs"
>
<div class="font-medium text-primary">{{ eventLabel(event) }}</div>
<div class="mt-0.5 text-[11px] text-muted">
<span v-if="event.occurred_at">{{ formatTime(event.occurred_at) }}</span>
<span v-if="event.stage_code" class="ml-1">· {{ event.stage_code }}</span>
</div>
<div v-if="event.reason" class="mt-1 text-[11px] text-secondary">{{ event.reason }}</div>
</li>
</ul>
<p v-else class="mt-2 text-xs text-muted">
{{ t('chat.shippingWorkflow.detail.eventsEmpty') }}
</p>
</section>
</template>
<p v-else class="text-xs text-muted">{{ t('chat.shippingWorkflow.detail.empty') }}</p>
</div>
<footer v-if="item && (canCancel || canReparse)" class="space-y-2 border-t border-default p-3">
<button
v-if="canReparse"
type="button"
class="w-full rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs font-medium text-amber-800 hover:bg-amber-100 disabled:opacity-50 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100"
:disabled="reparsing || cancelling"
data-testid="shipping-workflow-item-drawer-reparse"
@click="emit('reparse', item)"
>
{{ t('chat.shippingWorkflow.actions.reparse') }}
</button>
<button
v-if="canCancel"
type="button"
class="w-full rounded-md border border-rose-200 bg-rose-50 px-3 py-2 text-xs font-medium text-rose-700 hover:bg-rose-100 disabled:opacity-50 dark:border-rose-900/50 dark:bg-rose-950/40 dark:text-rose-200"
:disabled="cancelling || reparsing"
data-testid="shipping-workflow-item-drawer-cancel"
@click="emit('cancel', item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</footer>
</aside>
</div>
</Teleport>
</template>
@@ -0,0 +1,189 @@
<!--
features/chat/components/shipping/ShippingWorkflowReasonDialog.vue
用途:Workflow Item 取消 / 重识别的轻量原因确认弹窗(必填 reason)。
依赖:vue-i18n、dialog-overlay / dialog-panel 设计系统样式。
逻辑:由 ShippingWorkflowTimeline / DetailDrawer 以 v-model 控制;确认前校验非空原因。
-->
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
export type ShippingWorkflowReasonAction = 'cancel' | 'reparse';
const props = withDefaults(defineProps<{
modelValue: boolean;
action: ShippingWorkflowReasonAction;
confirmLoading?: boolean;
}>(), {
confirmLoading: false,
});
const emit = defineEmits<{
'update:modelValue': [value: boolean];
confirm: [payload: { reason: string; comment?: string }];
cancel: [];
}>();
const { t } = useI18n();
const reason = ref('');
const comment = ref('');
const reasonMissing = ref(false);
const reasonInputRef = ref<HTMLTextAreaElement | null>(null);
const title = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseTitle')
: t('chat.shippingWorkflow.reasonDialog.cancelTitle')
));
const confirmLabel = computed(() => (
props.action === 'reparse'
? t('chat.shippingWorkflow.reasonDialog.reparseConfirm')
: t('chat.shippingWorkflow.reasonDialog.cancelConfirm')
));
const reasonLabel = computed(() => t('chat.shippingWorkflow.reasonDialog.reasonLabel'));
const reasonRequiredHint = computed(() => t('chat.shippingWorkflow.reasonRequired'));
/**
* 关闭弹窗并重置本地表单。
*/
function closeDialog() {
emit('update:modelValue', false);
}
/**
* 取消:关闭并通知父级。
*/
function handleCancel() {
emit('cancel');
closeDialog();
}
/**
* 校验必填原因后提交。
*/
function handleConfirm() {
reasonMissing.value = false;
const trimmed = reason.value.trim();
if (!trimmed) {
reasonMissing.value = true;
return;
}
const trimmedComment = comment.value.trim();
emit('confirm', {
reason: trimmed,
comment: trimmedComment || undefined,
});
}
/**
* Escape 关闭弹窗。
*/
function onKeydown(event: KeyboardEvent) {
if (!props.modelValue) return;
if (event.key === 'Escape') {
event.preventDefault();
handleCancel();
}
}
watch(
() => props.modelValue,
async (open) => {
if (typeof document === 'undefined') return;
if (open) {
reason.value = '';
comment.value = '';
reasonMissing.value = false;
document.addEventListener('keydown', onKeydown, true);
await nextTick();
reasonInputRef.value?.focus();
return;
}
document.removeEventListener('keydown', onKeydown, true);
},
);
onBeforeUnmount(() => {
if (typeof document !== 'undefined') {
document.removeEventListener('keydown', onKeydown, true);
}
});
</script>
<template>
<Teleport to="body">
<div
v-if="modelValue"
class="dialog-overlay z-50 flex items-center justify-center p-4"
data-testid="shipping-workflow-reason-dialog"
@click.self="handleCancel"
>
<div
class="dialog-panel w-full max-w-md space-y-3 p-5"
role="dialog"
aria-modal="true"
:aria-label="title"
>
<h3 class="text-sm font-semibold text-primary">{{ title }}</h3>
<p class="mt-1 text-xs text-secondary">
{{ t('chat.shippingWorkflow.reasonDialog.impact') }}
</p>
<label class="mt-3 block text-xs text-secondary">
{{ reasonLabel }}
<span class="text-rose-600">*</span>
<textarea
ref="reasonInputRef"
v-model="reason"
rows="3"
class="input-field mt-1 w-full py-1.5 text-xs"
:aria-invalid="reasonMissing"
data-testid="shipping-workflow-reason-input"
:placeholder="t('chat.shippingWorkflow.reasonDialog.reasonPlaceholder')"
/>
</label>
<p v-if="reasonMissing" class="mt-1 text-[11px] text-rose-600" data-testid="shipping-workflow-reason-missing">
{{ reasonRequiredHint }}
</p>
<label
v-if="action === 'reparse'"
class="mt-2 block text-xs text-secondary"
>
{{ t('chat.shippingWorkflow.reasonDialog.commentOptional') }}
<textarea
v-model="comment"
rows="2"
class="input-field mt-1 w-full py-1.5 text-xs"
data-testid="shipping-workflow-comment-input"
/>
</label>
<div class="mt-4 flex flex-wrap justify-end gap-2">
<button
type="button"
class="btn-secondary btn-sm"
:disabled="confirmLoading"
data-testid="shipping-workflow-reason-cancel"
@click="handleCancel"
>
{{ t('chat.shippingWorkflow.reasonDialog.dismiss') }}
</button>
<button
type="button"
class="btn-danger btn-sm"
:disabled="confirmLoading"
data-testid="shipping-workflow-reason-confirm"
@click="handleConfirm"
>
{{ confirmLoading
? t('chat.shippingWorkflow.reasonDialog.submitting')
: confirmLabel }}
</button>
</div>
</div>
</div>
</Teleport>
</template>
@@ -0,0 +1,223 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.spec.ts
* 用途:验证右侧 Workflow 时间线分组、文件名、批次切换、过滤与取消/重识别弹窗。
* 依赖:Vitest、Vue Test Utils、vue-i18n、shipping.api mock。
* 逻辑:断言 layout_parsing 可见;文件名优先;仅看待处理过滤;原因弹窗提交 cancelItem。
*/
import { mount, flushPromises } from '@vue/test-utils';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { createI18n } from 'vue-i18n';
import { ref } from 'vue';
import chatZhCn from '@/locales/zh-CN/chat.json';
import ShippingWorkflowTimeline from './ShippingWorkflowTimeline.vue';
import type { ShippingWorkflow, ShippingWorkflowItem } from '../../types/shipping.api.types';
import type { UseShippingNoticeWorkflowReturn } from '../../shipping/useShippingNoticeWorkflow';
vi.mock('@/features/chat/api/shipping.api', () => ({
getWorkspaceShippingWorkflowItem: vi.fn(async (itemNo: string) => ({
item_no: itemNo,
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 1,
current_document_id: 1,
current_document_filename: 'detail.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
events: [],
})),
listWorkspaceShippingWorkflows: vi.fn(),
cancelWorkspaceShippingWorkflowItem: vi.fn(),
reparseWorkspaceShippingWorkflowItem: vi.fn(),
}));
vi.mock('@/shared/composables/useMessage', () => ({
useMessage: () => ({
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
info: vi.fn(),
}),
}));
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: { 'zh-CN': { chat: chatZhCn, errors: { generic: '错误' } } },
});
function buildItem(patch: Partial<ShippingWorkflowItem> = {}): ShippingWorkflowItem {
return {
item_no: 'SWI-1',
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
root_document_id: 10,
current_document_id: 10,
current_document_filename: 'shipping-notice.pdf',
current_version_no: 1,
lifecycle_status: 'layout_parsing',
current_stage: 'layout_parsing',
lock_version: 1,
...patch,
};
}
function buildController(
items: ShippingWorkflowItem[],
extras?: { workflows?: ShippingWorkflow[] },
): UseShippingNoticeWorkflowReturn {
const workflowList = extras?.workflows ?? [{
workflow_no: 'SNWF-1',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: {
total: items.length,
processing: items.filter((i) => i.lifecycle_status === 'layout_parsing' || i.lifecycle_status === 'extracting').length,
pending_review: items.filter((i) => i.lifecycle_status === 'pending_review').length,
failed: items.filter((i) => i.lifecycle_status === 'failed' || i.lifecycle_status === 'reparse_failed').length,
completed: items.filter((i) => i.lifecycle_status === 'closed').length,
},
items,
}];
const selectedWorkflowNo = ref(workflowList[0]?.workflow_no || null);
const workflows = ref(workflowList);
const workflow = ref(workflowList[0] || null);
const itemRef = ref(items);
return {
workflows,
selectedWorkflowNo,
selectWorkflow: vi.fn((no: string) => {
selectedWorkflowNo.value = no;
workflow.value = workflows.value.find((row) => row.workflow_no === no) || null;
itemRef.value = workflow.value?.items || [];
}),
workflow,
items: itemRef,
loading: ref(false),
error: ref(null),
refresh: vi.fn(async () => undefined),
cancelItem: vi.fn(async () => null),
reparseItem: vi.fn(async () => null),
stop: vi.fn(),
};
}
describe('ShippingWorkflowTimeline', () => {
beforeEach(() => {
document.body.innerHTML = '';
});
it('shows layout_parsing items with filename before review case exists', async () => {
const controller = buildController([
buildItem({
item_no: 'SWI-LAYOUT',
lifecycle_status: 'layout_parsing',
current_case_no: null,
current_document_filename: 'layout.pdf',
}),
buildItem({ item_no: 'SWI-REVIEW', lifecycle_status: 'pending_review', current_case_no: 'SNRC-1' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-LAYOUT"]').text()).toContain('layout.pdf');
expect(wrapper.text()).toContain('尚无复核单');
expect(wrapper.find('[data-testid="shipping-workflow-group-processing"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-group-pending_review"]').exists()).toBe(true);
});
it('filters to actionable items when pending-only is checked', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-A', lifecycle_status: 'extracting' }),
buildItem({ item_no: 'SWI-B', lifecycle_status: 'pending_review' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
await wrapper.find('[data-testid="shipping-workflow-pending-only-filter"]').setValue(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-B"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="shipping-workflow-item-SWI-A"]').exists()).toBe(false);
});
it('cancels an item via in-app reason dialog', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-CANCEL', lifecycle_status: 'extracting', lock_version: 3 }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: {
plugins: [i18n],
stubs: {
// 让 Teleport 就地渲染,便于 setValue / trigger
teleport: true,
},
},
});
await flushPromises();
await wrapper.find('[data-testid="shipping-workflow-action-cancel"]').trigger('click');
await flushPromises();
const reasonInput = wrapper.find('[data-testid="shipping-workflow-reason-input"]');
expect(reasonInput.exists()).toBe(true);
await reasonInput.setValue('cancel reason');
await wrapper.find('[data-testid="shipping-workflow-reason-confirm"]').trigger('click');
await flushPromises();
expect(controller.cancelItem).toHaveBeenCalledWith('SWI-CANCEL', {
reason: 'cancel reason',
expected_lock_version: 3,
});
});
it('shows batch switcher for multiple workflows', async () => {
const itemsA = [buildItem({ item_no: 'SWI-A', workflow_no: 'SNWF-A' })];
const itemsB = [buildItem({ item_no: 'SWI-B', workflow_no: 'SNWF-B', lifecycle_status: 'failed' })];
const workflows = [
{
workflow_no: 'SNWF-A',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'layout_parsing',
lock_version: 1,
counts: { total: 1, processing: 1, pending_review: 0, failed: 0, completed: 0 },
items: itemsA,
},
{
workflow_no: 'SNWF-B',
conversation_id: 'conv-1',
status: 'open',
current_stage: 'failed',
lock_version: 1,
counts: { total: 1, processing: 0, pending_review: 0, failed: 1, completed: 0 },
items: itemsB,
},
];
const controller = buildController(itemsA, { workflows });
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-batch-switcher"]').exists()).toBe(true);
await wrapper.find('[data-testid="shipping-workflow-batch-SNWF-B"]').trigger('click');
expect(controller.selectWorkflow).toHaveBeenCalledWith('SNWF-B');
});
it('shows reparse action for failed items', async () => {
const controller = buildController([
buildItem({ item_no: 'SWI-FAIL', lifecycle_status: 'failed', current_document_filename: 'bad.pdf' }),
]);
const wrapper = mount(ShippingWorkflowTimeline, {
props: { conversationId: 'conv-1', controller },
global: { plugins: [i18n] },
});
await flushPromises();
expect(wrapper.find('[data-testid="shipping-workflow-action-reparse"]').exists()).toBe(true);
});
});
@@ -0,0 +1,568 @@
/**
* features/chat/components/shipping/ShippingWorkflowTimeline.vue
* 用途:聊天页右侧「本次处理」面板——以会话 Workflow / Items 为列表事实源。
* 依赖:vue-i18n、useMessage、useShippingNoticeWorkflow(inject 或自建)、DetailDrawer、ReasonDialog。
* 逻辑:多批次时展示切换器;Items 以文件名为主标题;
* 分组进行中/待处理/待复核/待人工上传登记/失败/已完成(登记前不得进已完成);
* 「仅看待处理」过滤;查看进度 / 取消 / 重试重识别;取消与重识别用应用内原因弹窗。
*/
<script setup lang="ts">
import { computed, inject, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { ChevronDown, ChevronRight, RefreshCw } from 'lucide-vue-next';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
getWorkspaceShippingWorkflowItem,
} from '@/features/chat/api/shipping.api';
import type {
ShippingWorkflow,
ShippingWorkflowItem,
} from '@/features/chat/types/shipping.api.types';
import {
SHIPPING_WORKFLOW_KEY,
useShippingNoticeWorkflow,
type UseShippingNoticeWorkflowReturn,
} from '@/features/chat/shipping/useShippingNoticeWorkflow';
import ShippingWorkflowItemDetailDrawer from './ShippingWorkflowItemDetailDrawer.vue';
import ShippingWorkflowReasonDialog, {
type ShippingWorkflowReasonAction,
} from './ShippingWorkflowReasonDialog.vue';
const props = defineProps<{
conversationId?: string | null;
/** 父级递增以触发立即刷新。 */
refreshTrigger?: number;
/** 测试或父级注入时可直接传入控制器,跳过自建轮询。 */
controller?: UseShippingNoticeWorkflowReturn | null;
}>();
const { t, te, locale } = useI18n();
const msg = useMessage();
const injected = inject(SHIPPING_WORKFLOW_KEY, null);
/** 父级已 provide/传入时本地 composable 以空 conversationId 待机,避免双轮询。 */
const localController = useShippingNoticeWorkflow({
conversationId: () => (
props.controller || injected ? null : props.conversationId
),
refreshTrigger: () => (
props.controller || injected ? undefined : props.refreshTrigger
),
});
const ctl = computed((): UseShippingNoticeWorkflowReturn => (
props.controller || injected || localController
));
const collapsed = ref(false);
const pendingOnlyFilter = ref(false);
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);
const workflows = computed((): ShippingWorkflow[] => ctl.value.workflows.value);
const selectedWorkflowNo = computed(() => ctl.value.selectedWorkflowNo.value);
const workflow = computed((): ShippingWorkflow | null => ctl.value.workflow.value);
const items = computed((): ShippingWorkflowItem[] => ctl.value.items.value);
const loading = computed(() => ctl.value.loading.value);
const error = computed(() => ctl.value.error.value);
const counts = computed(() => workflow.value?.counts || {
total: items.value.length,
processing: 0,
pending_review: 0,
waiting_manual_upload: 0,
failed: 0,
completed: 0,
});
const showBatchSwitcher = computed(() => workflows.value.length > 1);
type ItemGroupKey =
| 'processing'
| 'queued'
| 'completed'
| 'pending_review'
| 'failed'
| 'waiting_manual_upload';
const PROCESSING_STATUSES = new Set([
'layout_parsing',
'extracting',
'building_order',
'inventory_matching',
'generating_excel',
]);
const QUEUED_STATUSES = new Set(['queued']);
const FAILED_STATUSES = new Set(['failed', 'reparse_failed']);
/** 真正完成/取消;待人工登记不是完成。 */
const COMPLETED_STATUSES = new Set(['closed', 'cancelled']);
const WAITING_MANUAL_UPLOAD_STATUSES = new Set(['manual_upload_pending']);
const PENDING_REVIEW_STATUSES = new Set(['pending_review']);
const ACTIONABLE_FILTER_STATUSES = new Set([
'pending_review',
'failed',
'reparse_failed',
'queued',
'manual_upload_pending',
]);
const REPARSE_STATUSES = new Set(['failed', 'reparse_failed', 'pending_review']);
/**
* 将 Item 归入展示分组。
*/
function resolveGroup(item: ShippingWorkflowItem): ItemGroupKey {
const status = String(item.lifecycle_status || '').trim();
if (PENDING_REVIEW_STATUSES.has(status)) return 'pending_review';
if (FAILED_STATUSES.has(status)) return 'failed';
if (WAITING_MANUAL_UPLOAD_STATUSES.has(status)) return 'waiting_manual_upload';
if (COMPLETED_STATUSES.has(status)) return 'completed';
if (QUEUED_STATUSES.has(status)) return 'queued';
if (PROCESSING_STATUSES.has(status)) return 'processing';
return 'processing';
}
/**
* 是否允许取消(非 closed/cancelled)。
*/
function canCancel(item: ShippingWorkflowItem): boolean {
return !COMPLETED_STATUSES.has(String(item.lifecycle_status || '').trim());
}
/**
* 是否允许重试/重新识别。
*/
function canReparse(item: ShippingWorkflowItem): boolean {
return REPARSE_STATUSES.has(String(item.lifecycle_status || '').trim());
}
/**
* 列表主标题:优先文件名。
*/
function itemTitle(item: ShippingWorkflowItem): string {
const filename = String(item.current_document_filename || '').trim();
if (filename) return filename;
return t('chat.shippingWorkflow.filenameFallback', {
docId: item.current_document_id,
});
}
const filteredItems = computed(() => {
if (!pendingOnlyFilter.value) return items.value;
return items.value.filter((item) =>
ACTIONABLE_FILTER_STATUSES.has(String(item.lifecycle_status || '').trim()),
);
});
const grouped = computed(() => {
const buckets: Record<ItemGroupKey, ShippingWorkflowItem[]> = {
processing: [],
queued: [],
pending_review: [],
waiting_manual_upload: [],
failed: [],
completed: [],
};
for (const item of filteredItems.value) {
buckets[resolveGroup(item)].push(item);
}
return buckets;
});
const groupOrder: ItemGroupKey[] = [
'processing',
'queued',
'pending_review',
'waiting_manual_upload',
'failed',
'completed',
];
/**
* 解析生命周期状态文案。
*/
function statusLabel(status: string): string {
const key = `chat.shippingWorkflow.itemStatus.${status}`;
return te(key) ? t(key) : status;
}
/**
* 格式化更新时间。
*/
function formatUpdatedLabel(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
const time = new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
return t('chat.shippingOrderExtractionDocumentTiming.updated', { time });
}
/**
* 格式化批次活动时间(切换器副文案)。
*/
function formatBatchTime(value?: string | null): string {
const date = new Date(String(value || ''));
if (Number.isNaN(date.getTime())) return '';
return new Intl.DateTimeFormat(String(locale.value || 'zh-CN'), {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
}).format(date);
}
/**
* 手动刷新。
*/
async function onRefresh() {
await ctl.value.refresh();
}
/**
* 切换批次。
*/
function onSelectWorkflow(workflowNo: string) {
ctl.value.selectWorkflow(workflowNo);
}
/**
* 打开详情:优先拉取含 events 的 Item 详情。
*/
async function openDetail(item: ShippingWorkflowItem) {
const itemNo = String(item.item_no || '').trim();
if (!itemNo) return;
detailOpen.value = true;
detailItem.value = item;
detailLoading.value = true;
try {
detailItem.value = await getWorkspaceShippingWorkflowItem(itemNo, {
include_events: true,
});
} catch {
/* 列表投影仍可展示 */
} finally {
detailLoading.value = false;
}
}
/**
* 打开取消原因弹窗。
*/
function openCancelDialog(item: ShippingWorkflowItem) {
reasonDialogItem.value = item;
reasonDialogAction.value = 'cancel';
reasonDialogOpen.value = true;
}
/**
* 打开重识别原因弹窗。
*/
function openReparseDialog(item: ShippingWorkflowItem) {
reasonDialogItem.value = item;
reasonDialogAction.value = 'reparse';
reasonDialogOpen.value = true;
}
/**
* 原因弹窗确认:按 action 取消或重识别。
*/
async function onReasonConfirm(payload: { reason: string; comment?: string }) {
const item = reasonDialogItem.value;
const itemNo = String(item?.item_no || '').trim();
if (!item || !itemNo || actionBusyItemNo.value) return;
actionBusyItemNo.value = itemNo;
try {
if (reasonDialogAction.value === 'reparse') {
await ctl.value.reparseItem(itemNo, {
reason: payload.reason,
comment: payload.comment,
});
} else {
await ctl.value.cancelItem(itemNo, {
reason: payload.reason,
expected_lock_version: item.lock_version,
});
}
reasonDialogOpen.value = false;
reasonDialogItem.value = null;
if (detailItem.value?.item_no === itemNo) {
detailOpen.value = false;
detailItem.value = null;
}
} catch (err) {
const message = err instanceof BusinessError ? err.message : t('errors.generic');
msg.error(message);
} finally {
actionBusyItemNo.value = null;
}
}
watch(
() => error.value,
() => {
/* 面板内展示 network_recoverable,不弹 toast */
},
);
</script>
<template>
<aside
class="flex w-72 shrink-0 flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.04)]"
data-testid="shipping-workflow-timeline"
>
<div class="flex w-full items-center gap-1 border-b border-default px-2 py-2">
<button
type="button"
class="flex min-w-0 flex-1 items-center justify-between gap-2 rounded-md px-1 py-1 text-left hover:bg-surface-muted/60"
@click="collapsed = !collapsed"
>
<div class="min-w-0">
<div class="text-sm font-semibold text-primary">
{{ t('chat.shippingWorkflow.title') }}
</div>
<div class="mt-0.5 text-xs text-secondary">
{{ t('chat.shippingWorkflow.pdfCount', { count: counts.total }) }}
</div>
</div>
<ChevronDown v-if="!collapsed" class="h-4 w-4 shrink-0 text-muted" />
<ChevronRight v-else class="h-4 w-4 shrink-0 text-muted" />
</button>
<button
type="button"
class="shrink-0 rounded-md p-1.5 text-muted hover:bg-surface-muted hover:text-primary disabled:opacity-50"
:disabled="loading"
:title="t('chat.shippingWorkflow.actions.refresh')"
data-testid="shipping-workflow-refresh"
@click="onRefresh"
>
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loading }" />
</button>
</div>
<div v-if="!collapsed" class="min-h-0 flex-1 overflow-auto p-3">
<div
v-if="showBatchSwitcher"
class="mb-3 space-y-1.5"
data-testid="shipping-workflow-batch-switcher"
>
<div class="text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t('chat.shippingWorkflow.batchSwitcherTitle') }}
</div>
<button
v-for="batch in workflows"
:key="batch.workflow_no"
type="button"
class="w-full rounded-lg border px-2.5 py-2 text-left transition"
:class="batch.workflow_no === selectedWorkflowNo
? 'border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-950/30'
: 'border-default bg-surface-soft/80 hover:bg-surface-muted/50'"
:data-testid="`shipping-workflow-batch-${batch.workflow_no}`"
@click="onSelectWorkflow(batch.workflow_no)"
>
<div class="truncate text-xs font-semibold text-primary">
{{ batch.workflow_no }}
</div>
<div class="mt-0.5 text-[11px] text-secondary">
{{ statusLabel(batch.current_stage) || batch.current_stage }}
· {{ t('chat.shippingWorkflow.batchCounts', {
processing: batch.counts.processing,
pending: batch.counts.pending_review,
waiting: batch.counts.waiting_manual_upload || 0,
failed: batch.counts.failed,
completed: batch.counts.completed,
}) }}
</div>
<div v-if="batch.last_activity_at" class="mt-0.5 text-[11px] text-muted">
{{ formatBatchTime(batch.last_activity_at) }}
</div>
</button>
</div>
<label class="mb-3 flex cursor-pointer items-center gap-2 text-[11px] text-secondary">
<input
v-model="pendingOnlyFilter"
type="checkbox"
class="rounded border-default"
data-testid="shipping-workflow-pending-only-filter"
/>
{{ t('chat.shippingWorkflow.pendingOnlyFilter') }}
</label>
<div class="mb-3 flex flex-wrap gap-1.5 text-[11px]">
<span class="rounded-md bg-sky-50 px-2 py-0.5 text-sky-700 dark:bg-sky-950/40 dark:text-sky-200">
{{ t('chat.shippingWorkflow.counts.processing', { count: counts.processing }) }}
</span>
<span
v-if="counts.pending_review > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
>
{{ t('chat.shippingWorkflow.counts.pendingReview', { count: counts.pending_review }) }}
</span>
<span
v-if="(counts.waiting_manual_upload || 0) > 0"
class="rounded-md bg-amber-50 px-2 py-0.5 text-amber-800 dark:bg-amber-950/40 dark:text-amber-100"
>
{{ t('chat.shippingWorkflow.counts.waitingManualUpload', {
count: counts.waiting_manual_upload || 0,
}) }}
</span>
<span class="rounded-md bg-emerald-50 px-2 py-0.5 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200">
{{ t('chat.shippingWorkflow.counts.completed', { count: counts.completed }) }}
</span>
<span
v-if="counts.failed > 0"
class="rounded-md bg-rose-50 px-2 py-0.5 text-rose-700 dark:bg-rose-950/40 dark:text-rose-200"
>
{{ t('chat.shippingWorkflow.counts.failed', { count: counts.failed }) }}
</span>
</div>
<div
v-if="workflow?.current_stage || workflow?.last_activity_at"
class="mb-3 text-[11px] text-secondary"
data-testid="shipping-workflow-stage-summary"
>
<span v-if="workflow?.current_stage">
{{ t('chat.shippingWorkflow.currentStage', {
stage: statusLabel(workflow.current_stage) || workflow.current_stage,
}) }}
</span>
<span v-if="workflow?.last_activity_at" class="ml-1">
· {{ formatUpdatedLabel(workflow.last_activity_at) }}
</span>
</div>
<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"
data-testid="shipping-workflow-network-error"
>
{{ t('chat.shippingWorkflow.networkRecoverable') }}
</div>
<div
v-else-if="error"
class="mb-3 rounded-md border border-rose-200 bg-rose-50 px-2.5 py-2 text-[11px] text-rose-800 dark:border-rose-900/60 dark:bg-rose-950/40 dark:text-rose-100"
>
{{ error }}
</div>
<div v-if="!filteredItems.length" class="text-xs text-muted">
{{ loading ? t('chat.shippingWorkflow.loading') : t('chat.shippingWorkflow.empty') }}
</div>
<template v-for="groupKey in groupOrder" :key="groupKey">
<section
v-if="grouped[groupKey].length"
class="mb-3"
:data-testid="`shipping-workflow-group-${groupKey}`"
>
<h3 class="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-secondary">
{{ t(`chat.shippingWorkflow.groups.${groupKey}`) }}
</h3>
<ul class="space-y-2">
<li
v-for="item in grouped[groupKey]"
:key="item.item_no"
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
:data-testid="`shipping-workflow-item-${item.item_no}`"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0">
<div
class="truncate text-xs font-semibold text-primary"
:title="itemTitle(item)"
data-testid="shipping-workflow-item-filename"
>
{{ itemTitle(item) }}
</div>
<div class="mt-0.5 text-[11px] text-muted">
{{ t('chat.shippingWorkflow.versionLabel', { version: item.current_version_no }) }}
· {{ statusLabel(String(item.current_stage || item.lifecycle_status || '')) }}
<span v-if="!item.current_case_no" class="ml-1 text-secondary">
· {{ t('chat.shippingWorkflow.noReviewCaseYet') }}
</span>
</div>
</div>
<span
class="shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-medium"
:class="{
'bg-amber-100 text-amber-800 dark:bg-amber-900/50 dark:text-amber-100':
groupKey === 'pending_review'
|| groupKey === 'failed'
|| groupKey === 'waiting_manual_upload',
'bg-sky-100 text-sky-800 dark:bg-sky-900/50 dark:text-sky-100':
groupKey === 'processing' || groupKey === 'queued',
'bg-emerald-100 text-emerald-800 dark:bg-emerald-900/50 dark:text-emerald-100':
groupKey === 'completed',
}"
>
{{ statusLabel(String(item.lifecycle_status || '')) }}
</span>
</div>
<div v-if="item.last_activity_at || item.updated_at" class="mt-0.5 text-[11px] text-muted">
{{ formatUpdatedLabel(item.last_activity_at || item.updated_at) }}
</div>
<div class="mt-2 flex flex-wrap gap-2">
<button
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
data-testid="shipping-workflow-action-view"
@click="openDetail(item)"
>
{{ t('chat.shippingWorkflow.actions.viewProgress') }}
</button>
<button
v-if="canReparse(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-amber-800 hover:underline disabled:opacity-50 dark:text-amber-200"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-reparse"
@click="openReparseDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.reparse') }}
</button>
<button
v-if="canCancel(item)"
type="button"
class="inline-flex items-center gap-1 text-[11px] font-medium text-rose-700 hover:underline disabled:opacity-50"
:disabled="actionBusyItemNo === item.item_no"
data-testid="shipping-workflow-action-cancel"
@click="openCancelDialog(item)"
>
{{ t('chat.shippingWorkflow.actions.cancelFile') }}
</button>
</div>
</li>
</ul>
</section>
</template>
</div>
<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"
/>
<ShippingWorkflowReasonDialog
v-model="reasonDialogOpen"
:action="reasonDialogAction"
:confirm-loading="Boolean(actionBusyItemNo)"
@confirm="onReasonConfirm"
/>
</aside>
</template>