feat(shipping-notice): 落地字段资产治理与唯一 Schema,自动建单随版本冻结
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
b7307fc573
commit
3a1dbf7ce5
144 files changed
+15167
-4480
No files matched your search
@@ -1,400 +1,829 @@
|
||||
/**
|
||||
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、ShippingBatchWorkspaceDrawer、chat.context。
|
||||
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
|
||||
|
||||
* 用途:对话页主区域,组合侧栏、消息列表、输入栏、货代会话任务摘要与内置浏览器。
|
||||
|
||||
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingSessionSummaryPanel、chat.context。
|
||||
|
||||
* 逻辑:本文件只做页面结构编排;货代 Chat 仅上传/进度通知,履约写操作不在本页;右侧摘要只读展示后端 ui_state/summary。
|
||||
|
||||
*/
|
||||
|
||||
<script setup lang="ts">
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Maximize2, Minimize2, Loader2 } from 'lucide-vue-next';
|
||||
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
|
||||
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
|
||||
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
|
||||
|
||||
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
|
||||
|
||||
import ShippingSessionSummaryPanel from '@/features/chat/components/ShippingSessionSummaryPanel.vue';
|
||||
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
|
||||
import ShippingOrderReviewView from '@/features/chat/views/ShippingOrderReviewView.vue';
|
||||
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
import { agentHasIntentUiProfile } from '@/shared/utils/agent-registry.utils';
|
||||
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
import {
|
||||
|
||||
MAINTENANCE_PANEL_DEFAULT_WIDTH,
|
||||
|
||||
buildMaintenancePanelWidthStyle,
|
||||
|
||||
clampMaintenancePanelWidth,
|
||||
|
||||
} from '@/features/maintenance/utils/maintenance-panel-layout.utils';
|
||||
|
||||
|
||||
|
||||
type MaintenanceRecordPanelCommand = {
|
||||
|
||||
mode: 'list' | 'create';
|
||||
|
||||
device: MaintenanceDevice;
|
||||
|
||||
nonce: number;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const isOrderReviewMode = computed(() => route.query.mode === 'order-review' && typeof route.query.run_no === 'string' && route.query.run_no.length > 0);
|
||||
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
|
||||
const isMaintenanceAgentPage = computed(() => agentHasIntentUiProfile(page.currentAgent, 'maintenance'));
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
const agent = page.currentAgent;
|
||||
if (!agent) return undefined;
|
||||
const url = agent.iframe_url;
|
||||
return url ? String(url) : undefined;
|
||||
});
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
|
||||
const activeExtractionRunNo = computed(() => {
|
||||
|
||||
// [STEP 1] 优先从消息流中的抽取状态卡取 run_no(终态后仍在消息里)。
|
||||
// page 经 reactive provide 后 messages 已解包为数组,禁止再读 .value。
|
||||
const messages = Array.isArray(page.messages) ? page.messages : [];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
|
||||
const item = messages[i];
|
||||
|
||||
if (!item || item.role !== 'assistant') continue;
|
||||
|
||||
const payload = item.payload && typeof item.payload === 'object' ? item.payload : null;
|
||||
|
||||
const fromPayload = payload && typeof (payload as { order_extraction_run_no?: unknown }).order_extraction_run_no === 'string'
|
||||
|
||||
? String((payload as { order_extraction_run_no: string }).order_extraction_run_no).trim()
|
||||
|
||||
: '';
|
||||
|
||||
if (fromPayload) return fromPayload;
|
||||
|
||||
if (item.shipping_order_extraction_state) {
|
||||
|
||||
const fromGetter = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromGetter) return fromGetter;
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
|
||||
// [STEP 2] 回退活动 Run(轮询中)与路由深链。
|
||||
|
||||
try {
|
||||
|
||||
const fromActive = String(page.getActiveOrderExtractionRunNo?.() || '').trim();
|
||||
|
||||
if (fromActive) return fromActive;
|
||||
|
||||
} catch {
|
||||
|
||||
/* ignore */
|
||||
|
||||
}
|
||||
|
||||
const fromQuery = typeof route.query.run_no === 'string' ? route.query.run_no.trim() : '';
|
||||
|
||||
return fromQuery;
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
const showShippingSessionSummary = computed(() => (
|
||||
|
||||
page.isShippingNoticeAgent
|
||||
|
||||
&& Boolean(
|
||||
|
||||
page.shippingBatchSummary
|
||||
|
||||
|| page.shippingConversationWorkspace?.batches?.length
|
||||
|
||||
|| activeExtractionRunNo.value
|
||||
|
||||
)
|
||||
|
||||
));
|
||||
|
||||
const embeddedIframeSrc = computed(() => {
|
||||
|
||||
const agent = page.currentAgent;
|
||||
|
||||
if (!agent) return undefined;
|
||||
|
||||
const url = agent.iframe_url;
|
||||
|
||||
return url ? String(url) : undefined;
|
||||
|
||||
});
|
||||
|
||||
const canManageMaintenance = computed(() => ['admin', 'maintenance_manager'].includes(String(page.currentUser?.role || '')));
|
||||
|
||||
const hideWelcomePanel = computed(() => false);
|
||||
|
||||
const hideWelcomeTitle = computed(() => isTrainingAgentPage.value);
|
||||
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
|
||||
const maintenanceEditRecord = ref<MaintenanceRecord | null>(null);
|
||||
|
||||
const maintenanceRecordPanelCommand = ref<MaintenanceRecordPanelCommand | null>(null);
|
||||
|
||||
const maintenancePanelWidth = ref(MAINTENANCE_PANEL_DEFAULT_WIDTH);
|
||||
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
|
||||
}
|
||||
|
||||
return buildMaintenancePanelWidthStyle(maintenancePanelWidth.value);
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
|
||||
|
||||
* @param event - 鼠标按下事件。
|
||||
|
||||
*/
|
||||
|
||||
const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
|
||||
if (isMaintenancePanelFullscreen.value) return;
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
isMaintenancePanelResizing.value = true;
|
||||
|
||||
const startX = event.clientX;
|
||||
|
||||
const startWidth = maintenancePanelWidth.value;
|
||||
|
||||
const handleMove = (moveEvent: MouseEvent) => {
|
||||
|
||||
const nextWidth = startWidth + (startX - moveEvent.clientX);
|
||||
|
||||
maintenancePanelWidth.value = clampMaintenancePanelWidth(nextWidth, window.innerWidth);
|
||||
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
|
||||
isMaintenancePanelResizing.value = false;
|
||||
|
||||
window.removeEventListener('mousemove', handleMove);
|
||||
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
window.addEventListener('mousemove', handleMove);
|
||||
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开右侧维修记录面板并进入指定记录的编辑表单。
|
||||
|
||||
* @param record - 会话结果表格中选中的维修记录。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordEdit = (record: MaintenanceRecord): void => {
|
||||
|
||||
maintenanceEditRecord.value = record;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鍒楄〃锛屽苟鎸夊綋鍓嶈澶囩紪鍙风瓫閫夊巻鍙茶褰曘€?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录列表,并按当前设备编号筛选历史记录。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordHistory = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'list', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 鎵撳紑鍙充晶缁翠慨璁板綍鏂板琛ㄥ崟锛屽苟棰勫~褰撳墠璁惧缂栧彿銆?
|
||||
* @param device - 浼氳瘽缁撴灉涓懡涓殑璁惧銆?
|
||||
|
||||
* 打开右侧维修记录新增表单,并预填当前设备编号。
|
||||
|
||||
* @param device - 会话结果中命中的设备。
|
||||
|
||||
*/
|
||||
|
||||
const openMaintenanceRecordCreate = (device: MaintenanceDevice): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = { mode: 'create', device, nonce: Date.now() };
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
/**
|
||||
|
||||
* 打开空白维修记录新增表单(不预填设备)。
|
||||
|
||||
*/
|
||||
|
||||
const openBlankMaintenanceRecordCreate = (): void => {
|
||||
|
||||
maintenanceEditRecord.value = null;
|
||||
|
||||
maintenanceRecordPanelCommand.value = null;
|
||||
|
||||
maintenancePanel.value = 'record';
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
// 切换非培训 Agent 时,重置工作区展开状态;培训 Agent 的默认展开策略交给 TrainingWorkspacePanel 按角色决定。
|
||||
|
||||
watch(() => page.currentAgentId, () => {
|
||||
|
||||
if (!isTrainingAgentPage.value) {
|
||||
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
|
||||
}
|
||||
|
||||
maintenancePanel.value = null;
|
||||
|
||||
isMaintenancePanelFullscreen.value = false;
|
||||
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
<template>
|
||||
|
||||
<ChatShell>
|
||||
|
||||
<template #overlay>
|
||||
|
||||
<div
|
||||
|
||||
v-if="page.isSidebarOpen && !page.isMobile"
|
||||
|
||||
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
|
||||
|
||||
@click="page.isSidebarOpen = false"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<template #sidebar>
|
||||
|
||||
<ChatSidebar
|
||||
|
||||
v-if="!page.isMobile"
|
||||
|
||||
v-model:collapsed="page.sidebarCollapsed"
|
||||
|
||||
v-model:agent-panel-open="page.showAgentPanel"
|
||||
|
||||
:is-open="page.isSidebarOpen"
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-agent-id="page.currentAgentId"
|
||||
|
||||
:agent-description="page.agentDescription"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:display-history="page.displayHistory"
|
||||
|
||||
:active-history-key="page.activeHistoryKey"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:applied-theme="page.appliedTheme"
|
||||
|
||||
@new-chat="page.handleSidebarNewChat"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@history-select="page.handleHistorySelect"
|
||||
|
||||
@clear-all-history="page.clearAllHistory"
|
||||
|
||||
@delete-history-item="page.deleteHistoryItem"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
@toggle-theme="page.toggleLightDark"
|
||||
|
||||
@open-feedback="page.showGeneralFeedbackDialog = true"
|
||||
|
||||
@go-workspace="page.goToWorkspace()"
|
||||
|
||||
@go-admin="page.goToAdmin"
|
||||
|
||||
@logout="page.handleLogout"
|
||||
|
||||
/>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
|
||||
<ChatMobileHeader
|
||||
|
||||
v-if="page.isMobile && page.currentAgent"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:active-agent-id="page.currentAgentId"
|
||||
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
|
||||
:user-agents="page.userAgents"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@go-history="page.goToWorkspace('history')"
|
||||
|
||||
@open-agent-popover="page.loadUserAgents"
|
||||
|
||||
@switch-agent="page.switchToAgent"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<div v-if="!page.currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
|
||||
|
||||
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
|
||||
|
||||
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div v-else-if="page.currentAgent.runtime_provider === 'iframe' || page.currentAgent.conversation_mode === 'embedded'" class="relative h-full w-full flex-1">
|
||||
|
||||
<iframe
|
||||
|
||||
:src="embeddedIframeSrc"
|
||||
|
||||
class="h-full w-full border-0 bg-surface"
|
||||
|
||||
allow="microphone; camera; clipboard-read; clipboard-write"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<template v-else>
|
||||
|
||||
<ShippingOrderReviewView v-if="isOrderReviewMode" />
|
||||
|
||||
<div v-else class="flex min-h-0 min-w-0 flex-1">
|
||||
|
||||
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
|
||||
<TrainingWorkspacePanel
|
||||
|
||||
:current-agent="page.currentAgent"
|
||||
|
||||
:current-user="page.currentUser"
|
||||
|
||||
:agent-guides="page.agentGuides"
|
||||
|
||||
:new-session-tick="page.viewId"
|
||||
|
||||
:training="page.training"
|
||||
|
||||
@open-guide="page.openGuideModal"
|
||||
|
||||
@update:expanded="isTrainingWorkspaceExpanded = $event"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchProgressPanel
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:workspace-open="page.shippingWorkspaceOpen"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@toggle-workspace="page.shippingWorkspaceOpen = !page.shippingWorkspaceOpen"
|
||||
/>
|
||||
|
||||
|
||||
<ChatMessageList
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
:messages="page.messages"
|
||||
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
|
||||
:suggested-questions-style="page.suggestedQuestionsStyle"
|
||||
|
||||
:styled-sections="page.styledSuggestedQuestionSections"
|
||||
|
||||
:suggested-questions="page.agentSuggestedQuestions"
|
||||
|
||||
:show-thinking-bubble="page.shouldShowThinkingBubble"
|
||||
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:show-chat-rating="page.showChatRating"
|
||||
|
||||
:copied-index="page.copiedIndex"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
|
||||
:handlers="page.messageBubbleHandlers"
|
||||
|
||||
:leave-handlers="page.leaveMessageHandlers"
|
||||
|
||||
:shipping-handlers="page.shippingMessageHandlers"
|
||||
|
||||
:training-handlers="page.trainingHandlers"
|
||||
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
|
||||
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
|
||||
|
||||
:get-message-run-progress="page.getMessageRunProgress"
|
||||
|
||||
:get-message-run-progress-error="page.getMessageRunProgressError"
|
||||
|
||||
:is-message-run-progress-loading="page.isMessageRunProgressLoading"
|
||||
|
||||
:tool-run-progress="page.toolRunProgress"
|
||||
|
||||
:tool-run-progress-title="page.toolRunProgressTitle"
|
||||
|
||||
:show-scroll-to-bottom="page.showScrollToBottom"
|
||||
|
||||
:hide-welcome-panel="hideWelcomePanel"
|
||||
|
||||
:hide-welcome-title="hideWelcomeTitle"
|
||||
|
||||
:pin-messages-to-bottom="!isTrainingAgentPage"
|
||||
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
|
||||
@edit="page.input = $event"
|
||||
|
||||
@resend="page.handleSend($event)"
|
||||
|
||||
@regenerate="page.regenerate"
|
||||
|
||||
@open-feedback="page.handleOpenFeedback($event)"
|
||||
|
||||
@select-question="page.handleSend"
|
||||
|
||||
@scroll-to-bottom="page.scrollToBottom"
|
||||
|
||||
@maintenance-edit-record="openMaintenanceRecordEdit"
|
||||
|
||||
@maintenance-view-record-history="openMaintenanceRecordHistory"
|
||||
|
||||
@maintenance-create-record-for-device="openMaintenanceRecordCreate"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<ChatInputBar
|
||||
|
||||
v-show="!isTrainingWorkspaceExpanded"
|
||||
|
||||
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
|
||||
|
||||
v-model="page.input"
|
||||
|
||||
v-model:selected-kb="page.selectedKb"
|
||||
|
||||
:attachments="page.attachments"
|
||||
|
||||
:attachment-policy="page.attachmentPolicy"
|
||||
|
||||
:available-kb-options="page.availableKbOptions"
|
||||
|
||||
:kb-dropdown-disabled="page.kbDropdownDisabled"
|
||||
|
||||
:is-thinking="page.isThinking"
|
||||
|
||||
:is-voice-recording="page.isVoiceRecording"
|
||||
|
||||
:is-voice-transcribing="page.isVoiceTranscribing"
|
||||
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
|
||||
:can-send-message="page.canSendMessage"
|
||||
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
|
||||
:can-manage-maintenance="canManageMaintenance"
|
||||
|
||||
:can-force-create-shipping-duplicate="page.canForceCreateShippingDuplicate"
|
||||
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||
:shipping-focus-reason="page.shippingFocusReason"
|
||||
|
||||
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
||||
|
||||
:shipping-notice-picker-ref-holder="page.shippingNoticePickerRefHolder"
|
||||
|
||||
:get-kb-label="page.getKbLabel"
|
||||
|
||||
@send="page.handleSend()"
|
||||
|
||||
@stop="page.stopActiveGeneration()"
|
||||
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
|
||||
@remove-attachment="page.removeAttachment"
|
||||
|
||||
@retry-attachment="page.retryAttachment"
|
||||
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
|
||||
@resolve-shipping-candidate-duplicate="page.resolveShippingCandidateDuplicate"
|
||||
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
|
||||
@maintenance-create-record="openBlankMaintenanceRecordCreate"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<ShippingSessionSummaryPanel
|
||||
|
||||
v-if="showShippingSessionSummary"
|
||||
|
||||
: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"
|
||||
|
||||
/>
|
||||
|
||||
|
||||
|
||||
<aside
|
||||
|
||||
v-if="isMaintenanceAgentPage && canManageMaintenance && maintenancePanel"
|
||||
|
||||
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
|
||||
|
||||
:class="[
|
||||
|
||||
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
|
||||
|
||||
isMaintenancePanelResizing ? 'select-none' : '',
|
||||
|
||||
]"
|
||||
|
||||
:style="maintenancePanelStyle"
|
||||
|
||||
>
|
||||
|
||||
<button
|
||||
|
||||
v-if="!isMaintenancePanelFullscreen"
|
||||
|
||||
type="button"
|
||||
|
||||
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
|
||||
|
||||
:title="$t('maintenance.panel.resizeTitle')"
|
||||
|
||||
@mousedown="startMaintenancePanelResize"
|
||||
|
||||
/>
|
||||
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
|
||||
<div>
|
||||
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
|
||||
|
||||
</h2>
|
||||
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
|
||||
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
|
||||
|
||||
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
|
||||
|
||||
>
|
||||
|
||||
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
|
||||
|
||||
<Maximize2 v-else class="h-4 w-4" />
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
||||
type="button"
|
||||
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
|
||||
|
||||
:title="$t('maintenance.panel.close')"
|
||||
|
||||
@click="maintenancePanel = null"
|
||||
|
||||
>
|
||||
|
||||
×
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
|
||||
<MaintenanceRecordManagerPanel
|
||||
|
||||
v-else
|
||||
|
||||
:edit-record="maintenanceEditRecord"
|
||||
|
||||
:command="maintenanceRecordPanelCommand"
|
||||
|
||||
/>
|
||||
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
|
||||
|
||||
|
||||
<ChatBrowserPanel
|
||||
|
||||
v-model:open="page.browserPanelOpen"
|
||||
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
|
||||
:current-url="page.browserCurrentUrl"
|
||||
|
||||
:frame-key="page.browserFrameKey"
|
||||
|
||||
:panel-style="page.browserPanelStyle"
|
||||
|
||||
:is-resizing="page.isBrowserResizing"
|
||||
|
||||
@load="page.browser.loadPage"
|
||||
|
||||
@refresh="page.browser.refreshPage"
|
||||
|
||||
@open-new-tab="page.browser.openInNewTab"
|
||||
|
||||
@url-enter="page.browser.onUrlEnter"
|
||||
|
||||
@start-resize="page.browser.startResize"
|
||||
|
||||
@close="page.browser.close"
|
||||
|
||||
/>
|
||||
|
||||
<ShippingBatchWorkspaceDrawer
|
||||
v-if="page.showShippingProgressWorkspace && (page.shippingConversationWorkspace || page.shippingBatchSummary)"
|
||||
v-model:open="page.shippingWorkspaceOpen"
|
||||
:conversation-workspace="page.shippingConversationWorkspace"
|
||||
:active-batch-no="page.activeShippingBatchNo"
|
||||
:focused-task-no="page.focusedShippingTaskNo"
|
||||
:batch-summary="page.shippingBatchSummary"
|
||||
:batch-tasks="page.shippingBatchTasks"
|
||||
:active-task-detail="page.activeShippingTaskDetail"
|
||||
:retrying-pending="page.retryingShippingPendingTasks"
|
||||
:action-busy="page.shippingActionBusy"
|
||||
@switch-batch="page.switchShippingBatch"
|
||||
@focus-task="page.switchShippingFocusTask"
|
||||
@workspace-action="page.handleShippingWorkspaceAction"
|
||||
@query-shortage="page.queryShippingShortageDetails"
|
||||
@retry-pending="page.openRetryFailedConfirm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</template>
|
||||
|
||||
</ChatShell>
|
||||
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchProgressPanel.vue
|
||||
* 用途:发货通知聊天顶部轻量批次状态条,展示当前批次进度与工作台入口。
|
||||
* 依赖:shipping.api.types、vue-i18n、批次 retry API。
|
||||
* 逻辑:生成式执行摘要由聊天消息流承载;本组件只提供固定状态 chrome 和明确范围的批次操作。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { AlertTriangle, List, RefreshCw } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
workspaceOpen: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'switch-batch': [batchNo: string];
|
||||
'toggle-workspace': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const retryingPending = ref(false);
|
||||
|
||||
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'completed', 'closed']);
|
||||
const FAILED_PROCESS_STATUSES = new Set(['rejected', 'upload_failed']);
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
const focusedTaskNo = computed(() =>
|
||||
String(
|
||||
props.activeTaskDetail?.task_no
|
||||
|| props.batchSummary?.current_focus_task_no
|
||||
|| props.batchSummary?.process_summary?.current_task_no
|
||||
|| '',
|
||||
).trim(),
|
||||
);
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || null;
|
||||
const total = Number(summary?.total || props.batchSummary?.file_count || props.batchTasks.length || 0);
|
||||
const completed = Number(
|
||||
summary?.completed
|
||||
|| props.batchTasks.filter((task) => COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())).length
|
||||
|| 0,
|
||||
);
|
||||
const runningFallback = props.batchTasks.some(
|
||||
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
|
||||
) ? 1 : 0;
|
||||
const running = Number(summary?.running || runningFallback || 0);
|
||||
const taskAbnormal = props.batchTasks.filter((task) => {
|
||||
const status = String(task.process_status || '').trim();
|
||||
return FAILED_PROCESS_STATUSES.has(status)
|
||||
|| task.upload_status === 'failed'
|
||||
|| Boolean(task.review_status || task.pending_human_reason);
|
||||
}).length;
|
||||
const summaryAbnormal = Number(summary?.failed || 0) + Number((summary as { needs_human?: number })?.needs_human || 0);
|
||||
const abnormal = Math.max(taskAbnormal, summaryAbnormal);
|
||||
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running - abnormal)));
|
||||
return { total, completed, running, pending, abnormal };
|
||||
});
|
||||
|
||||
const abnormalCount = computed(() => processSummary.value.abnormal);
|
||||
|
||||
const progressPercent = computed(() =>
|
||||
processSummary.value.total
|
||||
? Math.round((processSummary.value.completed / processSummary.value.total) * 100)
|
||||
: 0,
|
||||
);
|
||||
|
||||
const executionStateMeta = computed(() => {
|
||||
if (abnormalCount.value > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.needsIntervention'),
|
||||
className: 'border-amber-100 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (processSummary.value.running > 0 || processSummary.value.pending > 0) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.runningState'),
|
||||
className: 'border-sky-100 bg-sky-50 text-brand-700',
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.completedState'),
|
||||
className: 'border-emerald-100 bg-emerald-50 text-emerald-700',
|
||||
};
|
||||
});
|
||||
|
||||
const activeTaskSteps = computed(() => (
|
||||
resolveShippingWorkflowSteps(props.activeTaskDetail)
|
||||
));
|
||||
const activeStepIndex = computed(() => {
|
||||
const index = activeTaskSteps.value.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return index >= 0 ? index : Math.max(0, activeTaskSteps.value.length - 1);
|
||||
});
|
||||
const activeStepLabel = computed(() => {
|
||||
const step = activeTaskSteps.value[activeStepIndex.value];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: activeStepIndex.value + 1,
|
||||
total: activeTaskSteps.value.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : '--';
|
||||
});
|
||||
|
||||
const blockingMeta = computed(() => {
|
||||
const task = props.activeTaskDetail;
|
||||
if (!task) return null;
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
if (processStatus === 'upload_failed' || task.upload_status === 'failed') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedUploadRetryable'),
|
||||
className: 'border-rose-200 bg-rose-50 text-rose-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedShortage'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedParseReview'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
if (reason || reviewStatus) {
|
||||
return {
|
||||
text: t('chat.shippingNoticeUi.blockedWaitingHuman'),
|
||||
className: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
const handleRetryPending = async () => {
|
||||
const batchNo = String(props.batchSummary?.batch_no || '').trim();
|
||||
if (!batchNo || retryingPending.value) return;
|
||||
retryingPending.value = true;
|
||||
try {
|
||||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||||
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||||
} finally {
|
||||
retryingPending.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="w-full px-3 pt-3 md:px-8 md:pr-10">
|
||||
<div
|
||||
class="mx-auto w-full max-w-4xl rounded-2xl border border-default bg-gradient-to-r from-sky-50 via-white to-emerald-50 px-6 py-4 shadow-sm"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs text-slate-500">
|
||||
<span class="font-mono font-semibold text-brand-700">{{ activeBatchNo || '--' }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.fileCount') }} {{ processSummary.total }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.completedCount') }} {{ processSummary.completed }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.runningCount') }} {{ processSummary.running }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.pendingCount') }} {{ processSummary.pending }}</span>
|
||||
<span>{{ t('chat.shippingNoticeUi.needsIntervention') }} {{ abnormalCount }}</span>
|
||||
<span
|
||||
class="rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="executionStateMeta.className"
|
||||
>
|
||||
{{ executionStateMeta.text }}
|
||||
</span>
|
||||
<span
|
||||
v-if="blockingMeta"
|
||||
class="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-semibold"
|
||||
:class="blockingMeta.className"
|
||||
>
|
||||
<AlertTriangle class="h-3 w-3" />
|
||||
{{ blockingMeta.text }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-secondary">
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentFocus') }}</span>
|
||||
<span class="font-mono font-semibold text-primary">{{ focusedTaskNo || '--' }}</span>
|
||||
</span>
|
||||
<span>
|
||||
<span class="text-muted">{{ t('chat.shippingNoticeUi.currentStepLabel') }}:</span>
|
||||
<span class="font-medium text-primary">{{ activeStepLabel }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-2 h-1.5 max-w-md overflow-hidden rounded-full bg-slate-200">
|
||||
<div
|
||||
class="h-full rounded-full bg-brand-500 transition-all"
|
||||
:style="{ width: `${progressPercent}%` }"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
v-if="batchSummary?.batch_no"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending"
|
||||
@click="handleRetryPending"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
|
||||
@click="emit('toggle-workspace')"
|
||||
>
|
||||
<List class="h-3.5 w-3.5" />
|
||||
{{ workspaceOpen ? t('chat.shippingNoticeUi.collapseTaskList') : t('chat.shippingNoticeUi.expandTaskList') }}
|
||||
<span class="text-brand-600">{{ workspaceOpen ? '▲' : '▼' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,798 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ShippingBatchWorkspaceDrawer.vue
|
||||
* 用途:发货通知 Agent 的右侧批次工作台抽屉,承载多批次切换、任务筛选、步骤诊断与统一动作入口。
|
||||
* 依赖:shippingStepper、shippingMenu、shipping.api.types、vue-i18n、lucide-vue-next。
|
||||
* 逻辑:上游传入会话级 workspace 与当前批次任务;本组件只渲染后端 `ui_state.action_buttons` 和查看类辅助入口。
|
||||
* 解析阶段诊断优先展示 `ui_state.summary.issues` 完整问题列表;「重试所有失败」仅 emit `retry-pending`,由父级打开确认弹窗后再调用 useChatShipping 执行。
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { RefreshCw, Target, X } from 'lucide-vue-next';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
resolveShippingWorkflowSteps,
|
||||
type ShippingWorkflowStepItem,
|
||||
} from '@/features/chat/shipping';
|
||||
import { sanitizeShippingRuntimeStatusText } from '@/features/chat/shipping/shippingText';
|
||||
import { reportShippingDebugEvent } from '@/features/chat/shipping/shippingDebugReporter';
|
||||
import {
|
||||
isShippingWorkspaceTerminalTask,
|
||||
resolveShippingWorkspaceActionButtons,
|
||||
} from '@/features/chat/shipping/shippingWorkspaceActions';
|
||||
import { hasShortageLines } from '@/features/chat/shipping/shippingShortageDetails';
|
||||
import type {
|
||||
ShippingBatchSummary,
|
||||
ShippingConversationWorkspace,
|
||||
ShippingChatAction,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
focusedTaskNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
retryingPending?: boolean;
|
||||
actionBusy?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean];
|
||||
'switch-batch': [batchNo: string];
|
||||
'focus-task': [taskNo: string];
|
||||
'workspace-action': [taskNo: string, action: ShippingChatAction];
|
||||
'query-shortage': [taskNo: string];
|
||||
'retry-pending': [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const activeFilter = ref<'all' | 'abnormal' | 'waitingHuman' | 'resumable' | 'completed'>('all');
|
||||
|
||||
// #region debug-point A:workspace-click
|
||||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||||
reportShippingDebugEvent('ShippingBatchWorkspaceDrawer.vue', hypothesisId, msg, data);
|
||||
// #endregion
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
|
||||
const isFailedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.upload_status === 'failed' || String(task.process_status || '').trim() === 'upload_failed';
|
||||
|
||||
const isCompletedTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
isShippingWorkspaceTerminalTask(task);
|
||||
|
||||
const isAbnormalTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task)
|
||||
&& (isFailedTask(task)
|
||||
|| Boolean(task.review_status || task.pending_human_reason)
|
||||
|| String(task.process_status || '').trim() === 'waiting_inventory');
|
||||
|
||||
const isWaitingHumanTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isFailedTask(task) && Boolean(task.review_status || task.pending_human_reason);
|
||||
|
||||
const isResumableTask = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
!isCompletedTask(task) && !isWaitingHumanTask(task) && (
|
||||
isFailedTask(task)
|
||||
|| ['created', 'parsed', 'inventory_ready', 'matched', 'waiting_upload'].includes(String(task.process_status || '').trim())
|
||||
);
|
||||
|
||||
const resolveWorkspaceActionButtons = (task: ShippingTaskSummary | ShippingTaskDetail): ShippingChatAction[] =>
|
||||
resolveShippingWorkspaceActionButtons(task);
|
||||
|
||||
const rpaRuntimeMode = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
String(task.rpa_runtime?.mode || '').trim().toLowerCase();
|
||||
|
||||
const rpaRuntimeLabel = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const mode = rpaRuntimeMode(task);
|
||||
if (mode === 'mock') return t('chat.shippingNoticeUi.rpaModeMock');
|
||||
if (mode === 'browser') return t('chat.shippingNoticeUi.rpaModeBrowser');
|
||||
return String(task.rpa_runtime?.label || '').trim() || t('chat.shippingNoticeUi.rpaModeUnknown');
|
||||
};
|
||||
|
||||
const rpaRuntimeBadgeClass = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
rpaRuntimeMode(task) === 'mock'
|
||||
? 'border-amber-200 bg-amber-50 text-amber-700'
|
||||
: 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的辅助动作按钮样式。
|
||||
* 核心逻辑:把“聚焦当前任务 / 查询缺口明细”降级成轻量辅助入口,避免与后端主业务动作抢视觉权重。
|
||||
* @param kind - 当前辅助动作的视觉类型
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceAssistButtonClass = (kind: 'focus' | 'shortage') => {
|
||||
if (kind === 'shortage') {
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-amber-200 bg-amber-50/90 px-2.5 py-1.5 text-xs font-semibold text-amber-700 transition-all hover:border-amber-300 hover:bg-amber-100 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
return 'inline-flex min-h-[32px] items-center justify-center gap-1.5 rounded-lg border border-slate-200 bg-slate-50/90 px-2.5 py-1.5 text-xs font-semibold text-slate-700 transition-all hover:border-brand-200 hover:bg-white hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
};
|
||||
|
||||
/**
|
||||
* 渲染工作台任务卡中的业务动作按钮样式。
|
||||
* 核心逻辑:主动作在右侧工作台里使用更强的卡片式按钮承载,优先突出 primary,secondary/danger 维持次级密度。
|
||||
* @param action - 后端返回的结构化动作按钮
|
||||
* @param total - 当前任务业务动作总数,用于控制按钮跨列布局
|
||||
* @returns 对应的 Tailwind class 字符串
|
||||
*/
|
||||
const resolveWorkspaceTaskActionClass = (action: ShippingChatAction, total: number) => {
|
||||
const spanClass = action.variant === 'primary' || total === 1 ? 'col-span-2' : 'col-span-1';
|
||||
if (action.variant === 'primary') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg bg-gradient-to-r from-brand-600 to-sky-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm transition-all hover:-translate-y-[1px] hover:from-brand-700 hover:to-sky-600 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
if (action.variant === 'danger') {
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-rose-200 bg-rose-50 px-3 py-1.5 text-sm font-semibold text-rose-700 transition-all hover:border-rose-300 hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
}
|
||||
return `${spanClass} inline-flex min-h-[36px] items-center justify-center rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-sm font-semibold text-slate-700 shadow-sm transition-all hover:border-brand-200 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60`;
|
||||
};
|
||||
|
||||
// #region debug-point A:workspace-action
|
||||
const emitWorkspaceAction = (
|
||||
task: ShippingTaskSummary | ShippingTaskDetail,
|
||||
action: ShippingChatAction,
|
||||
) => {
|
||||
void reportRetryRpaDebug('A', 'workspace action clicked', {
|
||||
actionId: String(action.id || ''),
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
taskNo: String(task.task_no || '').trim().toUpperCase(),
|
||||
processStatus: String(task.process_status || ''),
|
||||
pendingHumanReason: String(task.pending_human_reason || ''),
|
||||
focusedTaskNo: String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
});
|
||||
emit('workspace-action', task.task_no, action);
|
||||
};
|
||||
// #endregion
|
||||
|
||||
// #region debug-point A:workspace-busy-state
|
||||
watch(
|
||||
() => [Boolean(props.actionBusy), String(props.focusedTaskNo || ''), String(props.activeTaskDetail?.task_no || '')].join('|'),
|
||||
() => {
|
||||
void reportRetryRpaDebug('A', 'workspace busy state snapshot', {
|
||||
actionBusy: Boolean(props.actionBusy),
|
||||
focusedTaskNo: String(props.focusedTaskNo || '').trim().toUpperCase(),
|
||||
activeDetailTaskNo: String(props.activeTaskDetail?.task_no || '').trim().toUpperCase(),
|
||||
activeDetailStatus: String(props.activeTaskDetail?.process_status || ''),
|
||||
activeDetailPendingReason: String(props.activeTaskDetail?.pending_human_reason || ''),
|
||||
open: props.open,
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
// #endregion
|
||||
|
||||
const batchAbnormalCount = (batch: ShippingBatchSummary) => {
|
||||
const summary = batch.process_summary || {};
|
||||
return Number(summary.failed || 0) + Number((summary as { needs_human?: number }).needs_human || 0);
|
||||
};
|
||||
|
||||
const batchCompletedCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.completed || 0);
|
||||
|
||||
const batchTotalCount = (batch: ShippingBatchSummary) =>
|
||||
Number(batch.process_summary?.total || batch.file_count || 0);
|
||||
|
||||
const taskCounts = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
const completed = tasks.filter(isCompletedTask).length;
|
||||
const abnormal = tasks.filter(isAbnormalTask).length;
|
||||
const waitingHuman = tasks.filter(isWaitingHumanTask).length;
|
||||
const resumable = tasks.filter(isResumableTask).length;
|
||||
return {
|
||||
total: tasks.length,
|
||||
abnormal,
|
||||
waitingHuman,
|
||||
resumable,
|
||||
completed,
|
||||
};
|
||||
});
|
||||
|
||||
const filteredTasks = computed(() => {
|
||||
const tasks = props.batchTasks || [];
|
||||
if (activeFilter.value === 'abnormal') return tasks.filter(isAbnormalTask);
|
||||
if (activeFilter.value === 'waitingHuman') return tasks.filter(isWaitingHumanTask);
|
||||
if (activeFilter.value === 'resumable') return tasks.filter(isResumableTask);
|
||||
if (activeFilter.value === 'completed') return tasks.filter(isCompletedTask);
|
||||
return tasks;
|
||||
});
|
||||
|
||||
const isCurrentTask = (taskNo?: string | null) =>
|
||||
String(taskNo || '').trim().toUpperCase() === String(props.focusedTaskNo || props.activeTaskDetail?.task_no || '').trim().toUpperCase();
|
||||
|
||||
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
if (isCompletedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.completedState'), className: 'border-emerald-100 bg-emerald-50 text-emerald-700' };
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.status.uploadFailed'), className: 'border-rose-100 bg-rose-50 text-rose-700' };
|
||||
}
|
||||
if (isAbnormalTask(task)) {
|
||||
return { text: t('chat.shippingNoticeUi.pendingState'), className: 'border-amber-100 bg-amber-50 text-amber-700' };
|
||||
}
|
||||
return { text: t('chat.shippingNoticeUi.runningState'), className: 'border-sky-100 bg-sky-50 text-brand-700' };
|
||||
};
|
||||
|
||||
const taskWorkflowSteps = (task: ShippingTaskSummary | ShippingTaskDetail) => (
|
||||
resolveShippingWorkflowSteps(task)
|
||||
);
|
||||
|
||||
const taskStepNumber = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
resolveActiveStep(taskWorkflowSteps(task)) + 1;
|
||||
|
||||
const taskStepHeadline = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const steps = taskWorkflowSteps(task);
|
||||
const index = resolveActiveStep(steps);
|
||||
const step = steps[index];
|
||||
return step ? t('chat.shippingNoticeUi.stepHeadline', {
|
||||
current: index + 1,
|
||||
total: steps.length,
|
||||
label: step.label.startsWith('chat.') ? t(step.label) : step.label,
|
||||
}) : t('chat.shippingNoticeUi.stepFraction', { current: index + 1, total: steps.length });
|
||||
};
|
||||
|
||||
const currentStepProgress = (task: ShippingTaskSummary | ShippingTaskDetail) =>
|
||||
task.step_payload?.current_step_progress || null;
|
||||
|
||||
/**
|
||||
* 规范化工作台中的运行态诊断文案。
|
||||
* 核心逻辑:右侧工作台属于业务操作面,不展示“第几次重试”这类过程计数,只保留状态与建议。
|
||||
* @param text - 后端返回的 summary / progress / error 文本
|
||||
* @returns 面向业务用户的净化后文案
|
||||
*/
|
||||
const sanitizeDiagnosisCopy = (text: string | null | undefined) =>
|
||||
sanitizeShippingRuntimeStatusText(String(text || '').trim());
|
||||
|
||||
/**
|
||||
* 读取任务诊断卡要展示的全部问题列表。
|
||||
* 核心逻辑:优先消费后端 `ui_state.summary.issues`(解析阶段已汇总库存源+warnings);
|
||||
* 若缺失则回退到单一 error_message,保证旧数据仍有可读文案。
|
||||
*/
|
||||
const resolveTaskDiagnosisIssues = (task: ShippingTaskSummary | ShippingTaskDetail): string[] => {
|
||||
const uiIssues = task.ui_state?.summary?.issues;
|
||||
if (Array.isArray(uiIssues) && uiIssues.length) {
|
||||
return uiIssues
|
||||
.map((item) => sanitizeDiagnosisCopy(item))
|
||||
.filter(Boolean);
|
||||
}
|
||||
const fallback = sanitizeDiagnosisCopy(task.ui_state?.summary?.error_message || task.error_message);
|
||||
return fallback ? [fallback] : [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 解析右侧工作台诊断标题/建议/问题列表。
|
||||
* 核心逻辑:解析阶段若 issues 多于 1 条,使用「发现问题」标题并列出全部条目,避免只显示库存源一条。
|
||||
*/
|
||||
const resolveTaskDiagnosis = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const uiSummary = task.ui_state?.summary;
|
||||
const issues = resolveTaskDiagnosisIssues(task);
|
||||
if (uiSummary?.title || uiSummary?.message || uiSummary?.error_message || issues.length) {
|
||||
const multiIssue = issues.length > 1;
|
||||
return {
|
||||
title: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesTitle', { count: issues.length })
|
||||
: (
|
||||
sanitizeDiagnosisCopy(issues[0] || uiSummary?.error_message || uiSummary?.title)
|
||||
|| t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step: taskStepNumber(task) })
|
||||
),
|
||||
advice: multiIssue
|
||||
? t('chat.shippingNoticeUi.diagnosisIssuesAdvice')
|
||||
: (sanitizeDiagnosisCopy(uiSummary?.message) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice')),
|
||||
issues: multiIssue ? issues : [],
|
||||
};
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
const processStatus = String(task.process_status || '').trim();
|
||||
const explicitError = String(task.error_message || '').trim();
|
||||
const progress = currentStepProgress(task);
|
||||
const progressMessage = String(progress?.message || '').trim();
|
||||
const progressDetail = String(progress?.detail || '').trim();
|
||||
const step = taskStepNumber(task);
|
||||
|
||||
if (isCompletedTask(task)) {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisCompletedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisCompletedAdvice'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && reason === 'rpa_pending') {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (explicitError) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(explicitError),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisAdviceRetryOrFocus'),
|
||||
};
|
||||
}
|
||||
if (progressMessage && (isAbnormalTask(task) || progress?.status === 'needs_human')) {
|
||||
return {
|
||||
title: sanitizeDiagnosisCopy(progressMessage),
|
||||
advice: sanitizeDiagnosisCopy(progressDetail) || t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
if (isFailedTask(task) || reason === 'upload_rpa_failed') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisUploadFailedTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisUploadFailedAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'shortage' || reason === 'shortage_review' || reviewStatus === 'shortage_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisShortageTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisShortageAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rpa_exhausted' || reason === 'rpa_pending' || reason === 'inv_unavail') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryRpaTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryRpaAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisParseReviewTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisParseReviewAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'rsv_required' || reviewStatus === 'rsv_required') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisReservationRequiredTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisReservationRequiredAdvice'),
|
||||
};
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
const resolution = (task as ShippingTaskDetail).inventory_source_resolution;
|
||||
const status = resolution && typeof resolution === 'object'
|
||||
? String((resolution as { status?: unknown }).status || '').trim()
|
||||
: '';
|
||||
const isAmbiguous = status === 'ambiguous';
|
||||
return {
|
||||
title: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousTitle'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceTitle'),
|
||||
advice: t(isAmbiguous
|
||||
? 'chat.shippingNoticeUi.diagnosisInventorySourceAmbiguousAdvice'
|
||||
: 'chat.shippingNoticeUi.diagnosisInventorySourceAdvice'),
|
||||
};
|
||||
}
|
||||
if (processStatus === 'waiting_inventory') {
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisInventoryWaitingTitle'),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisInventoryWaitingAdvice'),
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: t('chat.shippingNoticeUi.diagnosisStepWaitingTitle', { step }),
|
||||
advice: t('chat.shippingNoticeUi.diagnosisStepWaitingAdvice'),
|
||||
};
|
||||
};
|
||||
|
||||
const resolveSuggestedAction = (task: ShippingTaskSummary | ShippingTaskDetail) => {
|
||||
const actions = resolveWorkspaceActionButtons(task);
|
||||
if (actions.length) {
|
||||
return actions.map((action) => action.label).join(' / ');
|
||||
}
|
||||
const reason = String(task.pending_human_reason || '').trim();
|
||||
const reviewStatus = String(task.review_status || '').trim();
|
||||
if (hasShortageLines(task) || reason === 'shortage' || reviewStatus === 'shortage_review') {
|
||||
return t('chat.shippingNoticeUi.suggestShortageActions');
|
||||
}
|
||||
if (reason === 'low_confidence' || reviewStatus === 'parse_review') {
|
||||
return t('chat.shippingNoticeUi.suggestReviewParse');
|
||||
}
|
||||
if (reason === 'inventory_source_unresolved') {
|
||||
return t('chat.shippingNoticeUi.suggestConfirmInventorySource');
|
||||
}
|
||||
if (isFailedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestRetryStep');
|
||||
}
|
||||
if (isCompletedTask(task)) {
|
||||
return t('chat.shippingNoticeUi.suggestViewOnly');
|
||||
}
|
||||
return t('chat.shippingNoticeUi.suggestContinue');
|
||||
};
|
||||
|
||||
const resolveActiveStep = (steps: Array<ShippingWorkflowStepItem | { status: string }>) => {
|
||||
const activeIndex = steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
|
||||
return activeIndex >= 0 ? activeIndex : Math.max(0, steps.length - 1);
|
||||
};
|
||||
|
||||
const handleSwitchBatch = (batchNo: string) => {
|
||||
if (!batchNo || batchNo === activeBatchNo.value) return;
|
||||
activeFilter.value = 'all';
|
||||
emit('switch-batch', batchNo);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
v-if="open"
|
||||
class="hidden h-full w-[520px] shrink-0 flex-col border-l border-default bg-surface shadow-[-12px_0_40px_rgba(15,23,42,0.08)] lg:flex"
|
||||
>
|
||||
<header class="flex h-[92px] shrink-0 items-center justify-between border-b border-default px-6">
|
||||
<div>
|
||||
<div class="flex items-center gap-2 text-lg font-bold text-primary">
|
||||
<span class="grid h-5 w-5 grid-cols-2 gap-0.5 text-brand-500">
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm border border-current"></span>
|
||||
<span class="rounded-sm bg-current"></span>
|
||||
</span>
|
||||
{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}
|
||||
</div>
|
||||
<p class="mt-1 text-[11px] text-muted">{{ t('chat.shippingNoticeUi.batchWorkspaceSubtitle') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition hover:bg-surface-soft hover:text-primary"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="border-b border-default px-6 py-5">
|
||||
<div class="flex gap-3 overflow-x-auto pb-1">
|
||||
<button
|
||||
v-for="batch in workspaceBatches"
|
||||
:key="batch.batch_no"
|
||||
type="button"
|
||||
class="relative w-44 shrink-0 overflow-hidden rounded-xl border p-3 text-left transition-colors"
|
||||
:class="batch.batch_no === activeBatchNo ? 'border-brand-300 bg-surface shadow-sm ring-1 ring-brand-100' : 'border-default bg-transparent hover:bg-surface-soft'"
|
||||
@click="handleSwitchBatch(batch.batch_no)"
|
||||
>
|
||||
<div
|
||||
v-if="batch.batch_no === activeBatchNo"
|
||||
class="absolute left-0 top-0 h-1 w-full bg-brand-500"
|
||||
></div>
|
||||
<div class="mb-1 truncate font-mono text-xs font-bold text-primary">{{ batch.batch_no }}</div>
|
||||
<div class="text-[10px] font-medium text-muted">
|
||||
{{
|
||||
batchAbnormalCount(batch) > 0
|
||||
? t('chat.shippingNoticeUi.batchTabAbnormal', { completed: batchCompletedCount(batch), abnormal: batchAbnormalCount(batch) })
|
||||
: t('chat.shippingNoticeUi.batchTabNormal', { total: batchTotalCount(batch) })
|
||||
}}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-6 py-6">
|
||||
<section class="rounded-lg border border-default bg-surface p-4 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-primary">{{ t('chat.shippingNoticeUi.taskQueueTitle') }}</h3>
|
||||
<p class="mt-1 text-xs leading-5 text-muted">{{ t('chat.shippingNoticeUi.taskQueueHint') }}</p>
|
||||
<div class="mt-4">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-lg border border-default bg-white py-2 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="retryingPending || actionBusy"
|
||||
@click="emit('retry-pending')"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" :class="retryingPending ? 'animate-spin' : ''" />
|
||||
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryFailedTasks') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3 text-xs leading-5 text-indigo-900/80">
|
||||
{{ t('chat.shippingNoticeUi.batchActionSafetyNotice') }}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-6">
|
||||
<div class="mb-3 flex items-center justify-between gap-3">
|
||||
<h3 class="text-sm font-bold text-primary">
|
||||
{{ t('chat.shippingNoticeUi.taskDetailCount', { count: filteredTasks.length }) }}
|
||||
</h3>
|
||||
<div class="flex flex-wrap rounded-lg bg-slate-100 p-1 text-xs">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'all' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'all'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAll') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'abnormal' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'abnormal'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterAbnormal', { count: taskCounts.abnormal }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'waitingHuman' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'waitingHuman'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterWaitingHuman', { count: taskCounts.waitingHuman }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'resumable' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'resumable'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterResumable', { count: taskCounts.resumable }) }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded px-3 py-1 transition-colors"
|
||||
:class="activeFilter === 'completed' ? 'bg-white text-primary shadow-sm' : 'text-muted hover:text-secondary'"
|
||||
@click="activeFilter = 'completed'"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.filterCompleted', { count: taskCounts.completed }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!filteredTasks.length" class="py-10 text-center text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.emptyFilteredTasks') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<article
|
||||
v-for="task in filteredTasks"
|
||||
:key="task.task_no"
|
||||
class="relative overflow-hidden rounded-lg border bg-white p-3 shadow-sm transition-colors"
|
||||
:class="[
|
||||
isFailedTask(task) ? 'border-rose-100' : isAbnormalTask(task) ? 'border-amber-100' : 'border-default',
|
||||
isCurrentTask(task.task_no) ? 'ring-1 ring-brand-200' : '',
|
||||
]"
|
||||
>
|
||||
<div
|
||||
class="absolute left-0 top-0 h-full w-1"
|
||||
:class="isFailedTask(task) ? 'bg-rose-500' : isAbnormalTask(task) ? 'bg-amber-500' : 'bg-emerald-500'"
|
||||
></div>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate font-mono text-sm font-bold text-primary">
|
||||
{{ task.business_no || task.task_no }}
|
||||
</div>
|
||||
<div v-if="task.business_no" class="mt-0.5 truncate font-mono text-[10px] text-muted">
|
||||
{{ t('chat.shippingNoticeUi.technicalTaskNo', { taskNo: task.task_no }) }}
|
||||
</div>
|
||||
<div class="mt-0.5 truncate text-xs text-muted">
|
||||
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
|
||||
</div>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-1.5 text-xs font-medium text-secondary">
|
||||
<span>{{ taskStepHeadline(task) }}</span>
|
||||
<span
|
||||
v-if="task.rpa_runtime"
|
||||
class="rounded border px-1.5 py-0.5 text-[10px] font-bold leading-none"
|
||||
:class="rpaRuntimeBadgeClass(task)"
|
||||
>
|
||||
{{ rpaRuntimeLabel(task) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="rounded border px-2 py-1 text-[10px] font-bold" :class="resolveTaskStateMeta(task).className">
|
||||
{{ resolveTaskStateMeta(task).text }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="my-3">
|
||||
<div class="scheme-stepper">
|
||||
<template v-for="(step, index) in taskWorkflowSteps(task)" :key="step.id">
|
||||
<div
|
||||
class="scheme-step-node"
|
||||
:class="{
|
||||
done: step.status === 'completed',
|
||||
active: step.status === 'current',
|
||||
blocked: step.status === 'blocked',
|
||||
}"
|
||||
>
|
||||
<div class="scheme-step-dot">
|
||||
<span v-if="step.status === 'completed'">✓</span>
|
||||
<X v-else-if="step.status === 'blocked' && isFailedTask(task)" class="h-3 w-3" />
|
||||
<span v-else-if="step.status === 'blocked'">!</span>
|
||||
<span v-else>{{ index + 1 }}</span>
|
||||
</div>
|
||||
<div class="scheme-step-label">{{ step.label.startsWith('chat.') ? t(step.label) : step.label }}</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="diagnosis in [resolveTaskDiagnosis(task)]"
|
||||
:key="`${task.task_no}-diagnosis`"
|
||||
class="mb-2 rounded-lg border p-2.5 text-xs font-medium leading-5"
|
||||
:class="isFailedTask(task) ? 'border-rose-100 bg-rose-50 text-rose-700' : isAbnormalTask(task) ? 'border-amber-100 bg-amber-50 text-amber-700' : 'border-emerald-100 bg-emerald-50 text-emerald-700'"
|
||||
>
|
||||
<div class="font-semibold">{{ diagnosis.title }}</div>
|
||||
<ul
|
||||
v-if="(diagnosis.issues || []).length"
|
||||
class="mt-1.5 list-disc space-y-1 pl-4 font-normal text-slate-700"
|
||||
>
|
||||
<li
|
||||
v-for="(issue, issueIndex) in diagnosis.issues"
|
||||
:key="`${task.task_no}-issue-${issueIndex}`"
|
||||
>
|
||||
{{ issue }}
|
||||
</li>
|
||||
</ul>
|
||||
<div class="mt-1 font-normal text-slate-600">{{ diagnosis.advice }}</div>
|
||||
</div>
|
||||
<ShippingTaskParsedResultCard
|
||||
v-if="isCurrentTask(task.task_no) && activeTaskDetail"
|
||||
class="mb-3"
|
||||
:task-no="activeTaskDetail.task_no"
|
||||
:po-number="activeTaskDetail.po_number"
|
||||
:lines="activeTaskDetail.lines"
|
||||
:order-header="activeTaskDetail.order_header"
|
||||
:order-header-fields="activeTaskDetail.order_header_fields"
|
||||
:order-line-fields="activeTaskDetail.order_line_fields"
|
||||
:parse-validation="activeTaskDetail.parse_validation || activeTaskDetail.step_payload?.parse_validation || null"
|
||||
:process-field-gate="activeTaskDetail.process_field_gate || null"
|
||||
:source-candidate="activeTaskDetail.source_candidate || null"
|
||||
:field-conflicts="activeTaskDetail.field_conflicts || []"
|
||||
:order-data-version="activeTaskDetail.order_data_version"
|
||||
:default-expanded="isAbnormalTask(task) || isWaitingHumanTask(task)"
|
||||
compact
|
||||
@refreshed="emit('focus-task', activeTaskDetail.task_no)"
|
||||
/>
|
||||
<div v-if="!resolveWorkspaceActionButtons(task).length" class="mb-3 text-xs leading-5 text-muted">
|
||||
<span class="font-semibold text-secondary">{{ t('chat.shippingNoticeUi.suggestedAction') }}</span>
|
||||
{{ resolveSuggestedAction(task) }}
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-if="hasShortageLines(task)"
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('shortage')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('query-shortage', task.task_no)"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.queryShortageDetails') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:class="`${resolveWorkspaceAssistButtonClass('focus')} col-span-2`"
|
||||
:disabled="actionBusy"
|
||||
@click="emit('focus-task', task.task_no)"
|
||||
>
|
||||
<Target class="h-3.5 w-3.5" />
|
||||
{{ isCompletedTask(task) ? t('chat.shippingNoticeUi.viewDetail') : t('chat.shippingNoticeUi.switchCurrentTask') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="resolveWorkspaceActionButtons(task).length" class="mt-2 rounded-xl border border-slate-200/80 bg-slate-50/70 p-2">
|
||||
<div class="mb-1.5 px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-slate-500">
|
||||
{{ t('chat.shippingNoticeActionsHint') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-1.5">
|
||||
<button
|
||||
v-for="action in resolveWorkspaceActionButtons(task)"
|
||||
:key="`${task.task_no}-workspace-action-${action.id}-${action.source_code || ''}`"
|
||||
type="button"
|
||||
:class="resolveWorkspaceTaskActionClass(action, resolveWorkspaceActionButtons(task).length)"
|
||||
:disabled="actionBusy"
|
||||
@click="emitWorkspaceAction(task, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[90] bg-slate-900/30 backdrop-blur-sm lg:hidden"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
<aside
|
||||
class="ml-auto flex h-full w-[min(92vw,520px)] flex-col border-l border-default bg-surface shadow-2xl"
|
||||
@click.stop
|
||||
>
|
||||
<header class="flex h-16 shrink-0 items-center justify-between border-b border-default px-4">
|
||||
<div class="font-bold text-primary">{{ t('chat.shippingNoticeUi.batchWorkspaceTitle') }}</div>
|
||||
<button type="button" class="rounded-full p-2 text-muted hover:bg-surface-soft" @click="emit('update:open', false)">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</header>
|
||||
<div class="flex-1 overflow-y-auto p-4 text-sm text-muted">
|
||||
{{ t('chat.shippingNoticeUi.mobileWorkspaceHint') }}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.scheme-stepper {
|
||||
display: flex;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.scheme-step-node {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
min-width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.scheme-step-node:not(:last-child)::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 10px;
|
||||
left: calc(50% + 11px);
|
||||
width: calc(100% - 22px);
|
||||
height: 2px;
|
||||
background: #e2e8f0;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.scheme-step-node.done:not(:last-child)::after {
|
||||
background: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.active:not(:last-child)::after {
|
||||
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
|
||||
}
|
||||
|
||||
.scheme-step-dot {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
margin: 0 auto 0.25rem;
|
||||
border: 2px solid #e2e8f0;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
color: #64748b;
|
||||
font-size: 0.55rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.scheme-step-node.done .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
background: #0284c7;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-dot {
|
||||
border-color: #0284c7;
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
|
||||
color: #0284c7;
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-dot {
|
||||
border-color: #f59e0b;
|
||||
background: #fff;
|
||||
color: #f59e0b;
|
||||
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.18);
|
||||
}
|
||||
|
||||
.scheme-step-node.blocked .scheme-step-label {
|
||||
color: #d97706;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scheme-step-label {
|
||||
color: #64748b;
|
||||
font-size: 0.58rem;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.scheme-step-node.active .scheme-step-label {
|
||||
color: #0284c7;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,472 @@
|
||||
/**
|
||||
* features/chat/components/ShippingSessionSummaryPanel.vue
|
||||
* 用途:聊天页右侧「本次处理」唯一状态面——每 PDF 实时状态、异常原因与复核/已有任务深链。
|
||||
* 依赖:vue-i18n、vue-router、lucide、shipping.api(含 extraction documents)。
|
||||
* 逻辑:合并批次 Task 行与抽取 Run 文档行;open_existing 分流为「重复处理中 + 查看已有任务」。
|
||||
*/
|
||||
<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 {
|
||||
getWorkspaceShippingOrderReviewRun,
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
type ShippingBatchSummary,
|
||||
type ShippingConversationWorkspace,
|
||||
type ShippingTaskDetail,
|
||||
type ShippingTaskSummary,
|
||||
type ShippingTaskUiState,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type { ShippingOrderExtractionDocumentResult } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
const props = defineProps<{
|
||||
conversationWorkspace: ShippingConversationWorkspace | null;
|
||||
activeBatchNo: string;
|
||||
batchSummary: ShippingBatchSummary | null;
|
||||
batchTasks: ShippingTaskSummary[];
|
||||
activeTaskDetail: ShippingTaskDetail | null;
|
||||
/** 当前会话活跃抽取 Run;有值时右侧轮询每 PDF 状态 */
|
||||
extractionRunNo?: string | null;
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const collapsed = ref(false);
|
||||
const extractionDocs = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const docsLoading = ref(false);
|
||||
let docsTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const workspaceBatches = computed(() => props.conversationWorkspace?.batches || []);
|
||||
const activeBatchNo = computed(() =>
|
||||
String(props.activeBatchNo || props.batchSummary?.batch_no || workspaceBatches.value[0]?.batch_no || '').trim(),
|
||||
);
|
||||
|
||||
/**
|
||||
* 判断文档是否为「打开已有任务」分流。
|
||||
*/
|
||||
function isOpenExistingDoc(doc: ShippingOrderExtractionDocumentResult): boolean {
|
||||
const taskNo = String(doc.existing_task_no || '').trim();
|
||||
return Boolean(
|
||||
taskNo
|
||||
&& (
|
||||
doc.duplicate_resolution === 'open_existing'
|
||||
|| doc.available_actions.includes('open_existing')
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const processSummary = computed(() => {
|
||||
const summary = props.batchSummary?.process_summary || props.conversationWorkspace?.summary || null;
|
||||
const fromDocs = extractionDocs.value;
|
||||
const total = Number(
|
||||
(summary as { total?: number } | null)?.total
|
||||
|| props.batchSummary?.file_count
|
||||
|| props.batchTasks.length
|
||||
|| fromDocs.length
|
||||
|| 0,
|
||||
);
|
||||
const reviewFromDocs = fromDocs.filter((d) =>
|
||||
!isOpenExistingDoc(d)
|
||||
&& (
|
||||
d.status === 'review_required'
|
||||
|| d.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
),
|
||||
).length;
|
||||
const openExistingFromDocs = fromDocs.filter((d) => isOpenExistingDoc(d)).length;
|
||||
return {
|
||||
total,
|
||||
completed: Number((summary as { completed?: number } | null)?.completed || 0),
|
||||
running: Number((summary as { running?: number } | null)?.running || 0),
|
||||
failed: Number((summary as { failed?: number } | null)?.failed
|
||||
|| fromDocs.filter((d) => d.status === 'failed').length
|
||||
|| 0),
|
||||
needsHuman: Number(
|
||||
(summary as { needs_human?: number } | null)?.needs_human
|
||||
|| props.conversationWorkspace?.summary?.needs_human
|
||||
|| reviewFromDocs
|
||||
|| 0,
|
||||
),
|
||||
openExisting: openExistingFromDocs,
|
||||
pending: Number((summary as { pending?: number } | null)?.pending || 0),
|
||||
};
|
||||
});
|
||||
|
||||
type SummaryRow = {
|
||||
key: string;
|
||||
fileName: string;
|
||||
taskNo: string;
|
||||
runNo: string;
|
||||
caseNo: string;
|
||||
index: number;
|
||||
total: number;
|
||||
stage: string;
|
||||
message: string;
|
||||
entrySurface: string;
|
||||
/** exception=需人工异常;duplicate=已识别重复关联;none=无标签 */
|
||||
badge: 'exception' | 'duplicate' | 'none';
|
||||
kind: 'task' | 'document';
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 Task ui_state 映射为右侧行。
|
||||
*/
|
||||
function mapTaskRow(task: ShippingTaskSummary, index: number, total: number): SummaryRow {
|
||||
const uiState: ShippingTaskUiState | null | undefined =
|
||||
(props.activeTaskDetail?.task_no === task.task_no ? props.activeTaskDetail.ui_state : null)
|
||||
|| task.ui_state;
|
||||
const summary = uiState?.summary;
|
||||
const kind = String(uiState?.checkpoint_kind || summary?.checkpoint_kind || '');
|
||||
const stage = String(summary?.stage || summary?.title || task.process_status || '').trim();
|
||||
let normalizedStage = stage;
|
||||
if (kind === 'wait_manual_upload') normalizedStage = t('chat.shippingSessionSummary.waitingUpload');
|
||||
else if (kind === 'auto_continue') normalizedStage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
else if (kind === 'must_human') normalizedStage = stage || t('chat.shippingSessionSummary.needsReview');
|
||||
return {
|
||||
key: `task:${task.task_no || index}`,
|
||||
fileName: String(task.source_file_name || '').trim(),
|
||||
taskNo: String(task.task_no || '').trim(),
|
||||
runNo: '',
|
||||
caseNo: '',
|
||||
index: Number(task.batch_index || index + 1),
|
||||
total: Number(task.batch_total || total || 1),
|
||||
stage: normalizedStage,
|
||||
message: String(summary?.message || summary?.current_todo || summary?.pause_reason || '').trim(),
|
||||
entrySurface: String(summary?.entry_surface || 'none').trim(),
|
||||
badge: (
|
||||
summary?.pause_reason
|
||||
|| task.pending_human_reason
|
||||
|| task.error_message
|
||||
|| kind === 'must_human'
|
||||
|| ['rejected', 'upload_failed'].includes(String(task.process_status || ''))
|
||||
) ? 'exception' : 'none',
|
||||
kind: 'task',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 reason_code / review_details 拼成用户可读原因。
|
||||
*/
|
||||
function formatDocumentReason(doc: ShippingOrderExtractionDocumentResult): string {
|
||||
const reasonKey = `chat.shippingOrderExtractionReason.${doc.reason_code || ''}`;
|
||||
const reasonText = doc.reason_code && te(reasonKey)
|
||||
? t(reasonKey)
|
||||
: String(doc.reason_code || doc.activity_event_code || '').trim();
|
||||
const detailParts: string[] = [];
|
||||
for (const detail of (doc.review_details || []).slice(0, 2)) {
|
||||
const fieldCode = String(detail.field_code || '').trim();
|
||||
const fieldKey = `chat.shippingOrderExtractionReviewField.${fieldCode || 'unknown'}`;
|
||||
const fieldLabel = te(fieldKey) ? t(fieldKey) : (fieldCode || t('chat.shippingOrderExtractionReviewField.unknown'));
|
||||
const detailReasonKey = `chat.shippingOrderExtractionReason.${detail.reason_code || ''}`;
|
||||
const detailReason = detail.reason_code && te(detailReasonKey)
|
||||
? t(detailReasonKey)
|
||||
: String(detail.reason_code || '').trim();
|
||||
detailParts.push(
|
||||
t('chat.shippingOrderExtractionReviewDetail', {
|
||||
line: detail.line_number,
|
||||
field: fieldLabel,
|
||||
}) + (detailReason ? `(${detailReason})` : ''),
|
||||
);
|
||||
}
|
||||
if (reasonText && detailParts.length) return `${reasonText};${detailParts.join(';')}`;
|
||||
if (detailParts.length) return detailParts.join(';');
|
||||
return reasonText;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将抽取文档映射为建单前右侧行;open_existing 走任务深链。
|
||||
*/
|
||||
function mapDocumentRow(
|
||||
doc: ShippingOrderExtractionDocumentResult,
|
||||
index: number,
|
||||
total: number,
|
||||
runNo: string,
|
||||
caseNo = '',
|
||||
): SummaryRow {
|
||||
const existingTaskNo = String(doc.existing_task_no || '').trim();
|
||||
const openExisting = isOpenExistingDoc(doc);
|
||||
const needsReview = !openExisting && (
|
||||
doc.status === 'review_required'
|
||||
|| doc.available_actions.some((a) => a === 'review_candidate' || a === 'manual_review')
|
||||
|| Boolean(caseNo)
|
||||
);
|
||||
const failed = doc.status === 'failed';
|
||||
const reasonText = formatDocumentReason(doc);
|
||||
let stage = t('chat.shippingSessionSummary.autoProcessing');
|
||||
let entrySurface = 'none';
|
||||
let message = reasonText;
|
||||
let taskNo = '';
|
||||
if (openExisting && existingTaskNo) {
|
||||
stage = t('chat.shippingSessionSummary.duplicateProcessing');
|
||||
entrySurface = 'task_workbench';
|
||||
taskNo = existingTaskNo;
|
||||
message = reasonText
|
||||
? `${t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo })} · ${reasonText}`
|
||||
: t('chat.shippingSessionSummary.existingTaskNo', { taskNo: existingTaskNo });
|
||||
} else if (needsReview) {
|
||||
stage = t('chat.shippingSessionSummary.needsReview');
|
||||
entrySurface = 'review_workbench';
|
||||
} else if (failed) {
|
||||
stage = t('chat.shippingOrderExtractionDocumentStatus.failed');
|
||||
}
|
||||
return {
|
||||
key: `doc:${doc.unit_id || doc.document_id || index}`,
|
||||
fileName: String(doc.file_name || '').trim(),
|
||||
taskNo,
|
||||
runNo,
|
||||
caseNo,
|
||||
index: index + 1,
|
||||
total,
|
||||
stage,
|
||||
message,
|
||||
entrySurface,
|
||||
badge: openExisting ? 'duplicate' : (needsReview || failed ? 'exception' : 'none'),
|
||||
kind: 'document',
|
||||
};
|
||||
}
|
||||
|
||||
const caseNoByDocumentId = ref<Record<number, string>>({});
|
||||
|
||||
const taskRows = computed((): SummaryRow[] => {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
// [STEP 1] 建单前:有抽取 Run 时优先展示每 PDF 文档行(含复核/已有任务深链)。
|
||||
if (runNo && extractionDocs.value.length) {
|
||||
return extractionDocs.value.map((doc, index) =>
|
||||
mapDocumentRow(
|
||||
doc,
|
||||
index,
|
||||
extractionDocs.value.length,
|
||||
runNo,
|
||||
caseNoByDocumentId.value[Number(doc.document_id)] || '',
|
||||
));
|
||||
}
|
||||
// [STEP 2] 建单后:展示 Task 行。
|
||||
const tasks = props.batchTasks.length
|
||||
? props.batchTasks
|
||||
: (workspaceBatches.value.find((b) => b.batch_no === activeBatchNo.value)?.tasks || []);
|
||||
if (tasks.length) {
|
||||
return tasks.map((task, index) => mapTaskRow(task, index, processSummary.value.total || tasks.length));
|
||||
}
|
||||
return [];
|
||||
});
|
||||
|
||||
/**
|
||||
* 拉取当前 Run 文档与复核 Case,保证右侧可深链 case_no/run_no/existing_task_no。
|
||||
*/
|
||||
async function refreshExtractionDocs() {
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo || docsLoading.value) return;
|
||||
docsLoading.value = true;
|
||||
try {
|
||||
const [docsResponse, reviewResponse] = await Promise.all([
|
||||
listWorkspaceShippingOrderExtractionDocuments(runNo),
|
||||
getWorkspaceShippingOrderReviewRun(runNo).catch(() => null),
|
||||
]);
|
||||
extractionDocs.value = docsResponse.items || [];
|
||||
const mapping: Record<number, string> = {};
|
||||
for (const item of reviewResponse?.items || []) {
|
||||
const docId = Number(item.document_id);
|
||||
const caseNo = String(item.case_no || '').trim();
|
||||
if (docId && caseNo) mapping[docId] = caseNo;
|
||||
}
|
||||
caseNoByDocumentId.value = mapping;
|
||||
} catch {
|
||||
/* 右侧失败不打断聊天 */
|
||||
} finally {
|
||||
docsLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function stopDocsPolling() {
|
||||
if (docsTimer) clearInterval(docsTimer);
|
||||
docsTimer = null;
|
||||
}
|
||||
|
||||
function restartDocsPolling() {
|
||||
stopDocsPolling();
|
||||
const runNo = String(props.extractionRunNo || '').trim();
|
||||
if (!runNo) {
|
||||
extractionDocs.value = [];
|
||||
return;
|
||||
}
|
||||
void refreshExtractionDocs();
|
||||
docsTimer = setInterval(() => void refreshExtractionDocs(), 2000);
|
||||
}
|
||||
|
||||
watch(() => props.extractionRunNo, () => restartDocsPolling(), { immediate: true });
|
||||
onBeforeUnmount(stopDocsPolling);
|
||||
|
||||
/**
|
||||
* 打开任务处理工作台。
|
||||
*/
|
||||
async function openTaskWorkbench(taskNo: string) {
|
||||
const normalized = String(taskNo || '').trim();
|
||||
if (!normalized) return;
|
||||
await router.push({
|
||||
path: '/workspace/shipping-notice/my-tasks',
|
||||
query: { task_no: normalized },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开人工复核(Chat order-review 模式);携带 case_no 精确定位 PDF。
|
||||
*/
|
||||
async function openReview(runNo: string, caseNo = '') {
|
||||
const normalized = String(runNo || '').trim();
|
||||
if (!normalized) return;
|
||||
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: normalized,
|
||||
};
|
||||
const caseNormalized = String(caseNo || '').trim();
|
||||
if (caseNormalized) query.case_no = caseNormalized;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按 entry_surface 分发深链;复核必须有 run_no,禁止空 task 跳转。
|
||||
*/
|
||||
async function openEntrySurface(row: SummaryRow) {
|
||||
if (row.entrySurface === 'review_workbench') {
|
||||
const runNo = row.runNo || String(props.extractionRunNo || '');
|
||||
if (!runNo) return;
|
||||
await openReview(runNo, row.caseNo);
|
||||
return;
|
||||
}
|
||||
if (row.entrySurface === 'task_workbench' && row.taskNo) {
|
||||
await openTaskWorkbench(row.taskNo);
|
||||
}
|
||||
}
|
||||
</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 || taskRows.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">
|
||||
<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.openExisting > 0"
|
||||
class="rounded-md bg-violet-50 px-2 py-0.5 text-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.openExistingCount', { count: processSummary.openExisting }) }}
|
||||
</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="!taskRows.length" class="text-xs text-muted">
|
||||
{{ docsLoading ? t('chat.shippingOrderExtractionDocumentsLoading') : t('chat.shippingSessionSummary.empty') }}
|
||||
</div>
|
||||
|
||||
<ul v-else class="space-y-2">
|
||||
<li
|
||||
v-for="row in taskRows"
|
||||
:key="row.key"
|
||||
class="rounded-lg border border-default bg-surface-soft/80 px-2.5 py-2"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate text-xs font-semibold text-primary">
|
||||
{{ row.fileName || row.taskNo || t('chat.shippingSessionSummary.unnamedPdf') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] text-muted">
|
||||
{{ t('chat.shippingSessionSummary.progressIndex', {
|
||||
current: row.index,
|
||||
total: row.total || processSummary.total || 1,
|
||||
}) }}
|
||||
<!-- 重复态任务号已在原因行「已有任务 SN-xxx」展示,序号行不再重复 -->
|
||||
<span
|
||||
v-if="row.taskNo && row.badge !== 'duplicate'"
|
||||
class="ml-1 font-mono"
|
||||
>{{ row.taskNo }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
v-if="row.badge === 'duplicate'"
|
||||
class="shrink-0 rounded-full bg-violet-100 px-1.5 py-0.5 text-[10px] font-medium text-violet-800 dark:bg-violet-900/50 dark:text-violet-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.duplicateBadge') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="row.badge === 'exception'"
|
||||
class="shrink-0 rounded-full bg-amber-100 px-1.5 py-0.5 text-[10px] font-medium text-amber-800 dark:bg-amber-900/50 dark:text-amber-100"
|
||||
>
|
||||
{{ t('chat.shippingSessionSummary.exception') }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="row.stage" class="mt-1 text-[11px] text-secondary">
|
||||
{{ row.stage }}
|
||||
</div>
|
||||
<div v-if="row.message" class="mt-0.5 line-clamp-3 text-[11px] text-muted">
|
||||
{{ row.message }}
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="row.entrySurface === 'review_workbench'"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openEntrySurface(row)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ t('chat.shippingSessionSummary.openReview') }}
|
||||
</button>
|
||||
<button
|
||||
v-else-if="row.entrySurface === 'task_workbench' && row.taskNo"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 text-[11px] font-medium text-brand-700 hover:underline"
|
||||
@click="openTaskWorkbench(row.taskNo)"
|
||||
>
|
||||
<ExternalLink class="h-3 w-3" />
|
||||
{{ row.kind === 'document'
|
||||
? t('chat.shippingSessionSummary.openExistingTask')
|
||||
: t('chat.shippingSessionSummary.openTask') }}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;货代履约写按钮不在气泡内渲染,仅展示只读卡与深链通知。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
@@ -45,8 +45,6 @@ export interface ChatMessageBubbleHandlers {
|
||||
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
||||
getQueryPreviewSummary: (msg: ChatMessage) => string;
|
||||
openQueryPreviewDialog: (msg: ChatMessage) => void;
|
||||
shippingActionButtonClass: (variant?: string) => string;
|
||||
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
|
||||
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
|
||||
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
|
||||
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
|
||||
@@ -63,7 +61,6 @@ const {
|
||||
isThinking,
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
isLatestAssistantMessage,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
@@ -127,11 +124,6 @@ const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
));
|
||||
const showShippingActionsPanel = computed(() =>
|
||||
isShippingNoticeAgent
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const shippingOrderExtractionState = computed(() => message.shipping_order_extraction_state);
|
||||
const retryingOrderExtraction = ref(false);
|
||||
const shippingOrderExtractionRunNo = computed(() => {
|
||||
@@ -695,10 +687,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:match-status="handlers.getShippingMatchResultPayload(message)!.match_status"
|
||||
:line-results="handlers.getShippingMatchResultPayload(message)!.line_results"
|
||||
:shortage-lines="handlers.getShippingMatchResultPayload(message)!.shortage_lines"
|
||||
:action-buttons="handlers.getShippingMatchResultPayload(message)!.action_buttons"
|
||||
:action-busy="isThinking || message.shipping_actions_used"
|
||||
:action-button-class="handlers.shippingActionButtonClass"
|
||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||
/>
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
@@ -786,24 +774,6 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showShippingActionsPanel"
|
||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||
>
|
||||
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(action, actionIndex) in message.shipping_actions"
|
||||
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
|
||||
type="button"
|
||||
:class="handlers.shippingActionButtonClass(action.variant)"
|
||||
:disabled="isThinking || message.shipping_actions_used"
|
||||
@click="handlers.onShippingActionClick(message, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+44
-393
@@ -1,33 +1,15 @@
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.spec.ts
|
||||
* 用途:覆盖订单解析摘要卡、详情抽屉和单 PDF 结果项的关键交互。
|
||||
* 用途:覆盖聊天主区一句过程通知卡(无逐 PDF 列表、无复核按钮、无重复统计)。
|
||||
* 依赖:Vitest、Vue Test Utils、vue-i18n、本域组件与 DTO 类型。
|
||||
* 逻辑:验证按钮由后端 available_actions 驱动,详情抽屉按需加载并支持键盘关闭。
|
||||
* 逻辑:断言 processNotice 文案与技术失败重试;复核深链由右侧摘要面板承担。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createMemoryHistory, createRouter } from 'vue-router';
|
||||
import chatZhCn from '@/locales/zh-CN/chat.json';
|
||||
import ShippingOrderDocumentResultItem from './ShippingOrderDocumentResultItem.vue';
|
||||
import ShippingOrderExtractionCard from './ShippingOrderExtractionCard.vue';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
listDocuments: vi.fn(),
|
||||
listProgressEvents: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../api/shipping.api', () => ({
|
||||
listWorkspaceShippingOrderExtractionDocuments: api.listDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents: api.listProgressEvents,
|
||||
}));
|
||||
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -39,28 +21,15 @@ const i18n = createI18n({
|
||||
},
|
||||
});
|
||||
|
||||
const flushUi = async () => {
|
||||
await Promise.resolve();
|
||||
await nextTick();
|
||||
};
|
||||
|
||||
const makeRouter = () => createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/chat/:agentId', name: 'Chat', component: { template: '<div />' } },
|
||||
{ path: '/chat/:agentId/order-review/:runNo', name: 'ShippingOrderReview', component: { template: '<div />' } },
|
||||
],
|
||||
});
|
||||
|
||||
const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): ShippingOrderExtractionState => ({
|
||||
status: 'processing',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 1,
|
||||
completedDocuments: 2,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 1,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
},
|
||||
currentActivity: {
|
||||
@@ -68,7 +37,7 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
fileName: 'PO-450003.pdf',
|
||||
eventCode: 'profile_matching',
|
||||
},
|
||||
availableActions: ['view_details'],
|
||||
availableActions: [],
|
||||
terminal: false,
|
||||
refreshFailed: false,
|
||||
errorCode: null,
|
||||
@@ -77,383 +46,65 @@ const buildState = (patch: Partial<ShippingOrderExtractionState> = {}): Shipping
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildDocument = (
|
||||
patch: Partial<ShippingOrderExtractionDocumentResult> = {},
|
||||
): ShippingOrderExtractionDocumentResult => ({
|
||||
unit_id: 11,
|
||||
document_id: 85,
|
||||
file_name: 'PO-450001.pdf',
|
||||
status: 'candidate_ready',
|
||||
po_number: '450001',
|
||||
line_count: 4,
|
||||
profile: {
|
||||
code: 'vendor_a_po',
|
||||
name: 'Vendor A Purchase Order',
|
||||
version: 2,
|
||||
},
|
||||
email_supplement: {
|
||||
status: 'merged',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 0,
|
||||
reservation_id_status: 'merged',
|
||||
source_type_status: 'unavailable',
|
||||
},
|
||||
reason_code: null,
|
||||
available_actions: ['view_evidence', 'review_candidate'],
|
||||
...patch,
|
||||
});
|
||||
|
||||
const buildProgressEvent = (
|
||||
patch: Partial<ShippingOrderExtractionProgressEvent> = {},
|
||||
): ShippingOrderExtractionProgressEvent => ({
|
||||
event_code: 'expansion_wave_started',
|
||||
status: 'completed',
|
||||
unit_id: null,
|
||||
document_id: null,
|
||||
reason_code: null,
|
||||
summary: {
|
||||
selection_batch: 2,
|
||||
reason_codes: ['required_field_missing'],
|
||||
},
|
||||
occurred_at: '2026-07-28T10:30:00Z',
|
||||
...patch,
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = '';
|
||||
it('renders one-line process notice without per-PDF list, review CTA, or count stats', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState(), runNo: 'SNER-1' },
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.text()).toContain('正在处理附件');
|
||||
expect(wrapper.text()).toContain('右侧');
|
||||
expect(wrapper.text()).not.toContain('自动推进');
|
||||
expect(wrapper.text()).not.toContain('进入人工复核');
|
||||
expect(wrapper.findAll('[data-testid="shipping-order-document-result"]').length).toBe(0);
|
||||
});
|
||||
|
||||
it('refreshes documents whenever the details drawer is opened', async () => {
|
||||
api.listDocuments.mockResolvedValue({ items: [buildDocument()] });
|
||||
api.listProgressEvents.mockResolvedValue({ items: [buildProgressEvent()] });
|
||||
it('renders duplicate-linked notice when only open_existing results remain', () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
selectionPlan: {
|
||||
maxInitialAttachments: 2,
|
||||
maxInitialConcurrency: 2,
|
||||
expansionBatchSize: 2,
|
||||
maxTotalAttachments: 6,
|
||||
totalAttachmentCount: 5,
|
||||
eligibleAttachmentCount: 3,
|
||||
selectedAttachmentCount: 2,
|
||||
plannedAttachmentCount: 3,
|
||||
pendingExpansionAttachmentCount: 1,
|
||||
pendingExpansionBatches: { '2': 1 },
|
||||
skippedAttachmentCount: 3,
|
||||
duplicateAttachmentCount: 1,
|
||||
budgetLimitedAttachmentCount: 1,
|
||||
groupCount: 2,
|
||||
},
|
||||
unitSummary: {
|
||||
totalUnits: 2,
|
||||
selectedUnits: 2,
|
||||
retryingUnits: 1,
|
||||
pendingRetryUnits: 0,
|
||||
failedUnits: 0,
|
||||
reviewRequiredUnits: 0,
|
||||
succeededUnits: 0,
|
||||
selectionBatches: { '1': 2 },
|
||||
reviewRequiredReasonCodes: ['required_field_missing'],
|
||||
expansionTriggerReasonCodes: ['missing_reservation_id'],
|
||||
technicalFailureReasonCodes: [],
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-001',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const detailButton = wrapper.findAll('button').find((item) => item.text().includes('查看处理详情'));
|
||||
expect(detailButton).toBeTruthy();
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(1);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(1);
|
||||
expect(api.listDocuments).toHaveBeenCalledWith('SNER-001');
|
||||
expect(api.listProgressEvents).toHaveBeenCalledWith('SNER-001');
|
||||
expect(wrapper.text()).toContain('处理详情');
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('PO-450001.pdf');
|
||||
expect(wrapper.text()).toContain('本轮从 5 个附件中规划 2 个订单组');
|
||||
expect(wrapper.text()).toContain('已选 2 个附件');
|
||||
expect(wrapper.text()).toContain('待扩展 1 个附件');
|
||||
expect(wrapper.text()).toContain('预算受限 1 个');
|
||||
expect(wrapper.text()).toContain('技术重试 1 个');
|
||||
expect(wrapper.text()).toContain('待复核原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).toContain('扩批触发:仍缺少 Reservation 字段,需要后续附件补证。');
|
||||
|
||||
await detailButton!.trigger('click');
|
||||
await flushUi();
|
||||
|
||||
expect(api.listDocuments).toHaveBeenCalledTimes(2);
|
||||
expect(api.listProgressEvents).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('routes manual review directly to the dedicated workspace', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
availableActions: ['enter_manual_review'],
|
||||
}),
|
||||
runNo: 'SNER-002',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n, router],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { mode: 'order-review', run_no: 'SNER-002' },
|
||||
});
|
||||
expect(api.listDocuments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves the originating conversation when entering manual review', async () => {
|
||||
const router = makeRouter();
|
||||
await router.push({ name: 'Chat', params: { agentId: 'agent-1' }, query: { conversation_id: 'conv-123' } });
|
||||
await router.isReady();
|
||||
const pushSpy = vi.spyOn(router, 'push');
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: { state: buildState({ availableActions: ['enter_manual_review'] }), runNo: 'SNER-003' },
|
||||
global: { plugins: [i18n, router], stubs: { teleport: true } },
|
||||
});
|
||||
|
||||
const reviewButton = wrapper.findAll('button').find((item) => item.text().includes('进入人工复核'));
|
||||
expect(reviewButton).toBeTruthy();
|
||||
await reviewButton!.trigger('click');
|
||||
|
||||
await vi.waitFor(() => expect(pushSpy).toHaveBeenCalled());
|
||||
expect(pushSpy).toHaveBeenCalledWith({
|
||||
name: 'Chat',
|
||||
params: { agentId: 'agent-1' },
|
||||
query: { conversation_id: 'conv-123', mode: 'order-review', run_no: 'SNER-003' },
|
||||
});
|
||||
});
|
||||
|
||||
it('emits retry for failed attachments without mutating state locally', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
status: 'failed',
|
||||
terminal: true,
|
||||
status: 'review_required',
|
||||
summary: {
|
||||
totalDocuments: 3,
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 2,
|
||||
completedDocuments: 0,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 2,
|
||||
failedDocuments: 0,
|
||||
candidateCount: 0,
|
||||
openedExistingCount: 2,
|
||||
},
|
||||
currentActivity: null,
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
availableActions: ['view_details'],
|
||||
}),
|
||||
runNo: 'SNER-003',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
runNo: 'SNER-DUP',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
const retryButton = wrapper.findAll('button').find((item) => item.text().includes('重试失败附件'));
|
||||
expect(retryButton).toBeTruthy();
|
||||
|
||||
await retryButton!.trigger('click');
|
||||
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1);
|
||||
expect(wrapper.text()).toContain('发现重复文件');
|
||||
expect(wrapper.text()).toContain('已关联已有任务');
|
||||
expect(wrapper.text()).not.toContain('需人工处理');
|
||||
});
|
||||
|
||||
it('renders run-level activity text without forcing an unknown file label', async () => {
|
||||
it('emits retry for failed attachments only', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionCard, {
|
||||
props: {
|
||||
state: buildState({
|
||||
currentActivity: {
|
||||
unitId: 0,
|
||||
fileName: null,
|
||||
eventCode: 'plan_created',
|
||||
selectionBatch: 2,
|
||||
reasonCodes: ['required_field_missing'],
|
||||
availableActions: ['retry_failed_attachments'],
|
||||
summary: {
|
||||
totalDocuments: 2,
|
||||
pendingDocuments: 0,
|
||||
processingDocuments: 0,
|
||||
completedDocuments: 1,
|
||||
reviewRequiredDocuments: 0,
|
||||
failedDocuments: 1,
|
||||
candidateCount: 0,
|
||||
},
|
||||
}),
|
||||
runNo: 'SNER-004',
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
runNo: 'SNER-2',
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('识别计划已创建,正在准备首轮附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
expect(wrapper.text()).not.toContain('未命名 PDF');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderExtractionDetailsDrawer', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('closes on Escape when the drawer is open', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
open: false,
|
||||
state: buildState({
|
||||
status: 'partially_completed',
|
||||
terminal: true,
|
||||
availableActions: ['view_details', 'enter_manual_review'],
|
||||
}),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
await wrapper.setProps({ open: true });
|
||||
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
|
||||
await nextTick();
|
||||
|
||||
expect(wrapper.emitted('close')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders run timeline entries with batch and reason context', async () => {
|
||||
const wrapper = mount(ShippingOrderExtractionDetailsDrawer, {
|
||||
props: {
|
||||
open: true,
|
||||
state: buildState(),
|
||||
documents: [buildDocument()],
|
||||
progressEvents: [buildProgressEvent()],
|
||||
loading: false,
|
||||
loadFailed: false,
|
||||
progressLoading: false,
|
||||
progressLoadFailed: false,
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
stubs: {
|
||||
teleport: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('运行时间线');
|
||||
expect(wrapper.text()).toContain('业务复核');
|
||||
expect(wrapper.text()).toContain('系统已开始分析下一轮候选附件。');
|
||||
expect(wrapper.text()).toContain('当前批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('当前原因:订单关键字段不完整。');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ShippingOrderDocumentResultItem', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('renders business reason and server-declared actions for a review-required PDF', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'review_required',
|
||||
reason_code: 'multiple_po_detected',
|
||||
po_number: null,
|
||||
line_count: 0,
|
||||
email_supplement: {
|
||||
status: 'conflict',
|
||||
relation_codes: ['po_mpn'],
|
||||
conflict_count: 2,
|
||||
reservation_id_status: 'conflict',
|
||||
source_type_status: 'none',
|
||||
},
|
||||
available_actions: ['view_evidence', 'manual_review'],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('需要人工复核');
|
||||
expect(wrapper.text()).toContain('一份 PDF 中检测到多个不同 PO');
|
||||
expect(wrapper.text()).toContain('正文冲突 2 项');
|
||||
|
||||
const actionButtons = wrapper.findAll('button');
|
||||
expect(actionButtons.map((item) => item.text())).toEqual(
|
||||
expect.arrayContaining(['查看证据', '人工复核']),
|
||||
);
|
||||
|
||||
await actionButtons[0].trigger('click');
|
||||
|
||||
expect(wrapper.emitted('enterManualReview')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('renders a user-safe retry hint rather than a technical failure code for a failed attachment', async () => {
|
||||
const wrapper = mount(ShippingOrderDocumentResultItem, {
|
||||
props: {
|
||||
document: buildDocument({
|
||||
status: 'failed',
|
||||
reason_code: 'technical_failure',
|
||||
selection_batch: 2,
|
||||
group_key: 'PO-GRP-02',
|
||||
retry_status: 'failed',
|
||||
technical_failure_reason_code: 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
budget_cost: {
|
||||
initial_attachment_budget: 2,
|
||||
initial_concurrency_budget: 2,
|
||||
selected_in_batch: 1,
|
||||
},
|
||||
available_actions: [],
|
||||
}),
|
||||
},
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
},
|
||||
});
|
||||
|
||||
expect(wrapper.text()).toContain('选择批次:第 2 轮');
|
||||
expect(wrapper.text()).toContain('订单组:PO-GRP-02');
|
||||
expect(wrapper.text()).toContain('系统暂未完成处理,您可以稍后重试。');
|
||||
expect(wrapper.text()).toContain('首轮预算:附件 2 个,并发 2 个,本轮已选 1 个');
|
||||
expect(wrapper.text()).not.toContain('SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT');
|
||||
await wrapper.get('button').trigger('click');
|
||||
expect(wrapper.emitted('retry')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,14 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/shipping/ShippingOrderExtractionCard.vue
|
||||
* 用途:渲染聊天中的订单抽取摘要卡,并在需要时打开 PDF 详情抽屉。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、documents API、详情抽屉。
|
||||
* 逻辑:卡片只显示 Run 汇总、当前活动和下一步动作;逐 PDF 结果与 Run 事实时间线延迟到抽屉内按需加载。
|
||||
* 用途:聊天主区一句过程通知——不重复右侧统计,无逐 PDF 列表、无复核按钮。
|
||||
* 依赖:订单抽取 Run 状态卡 DTO、vue-i18n。
|
||||
* 逻辑:右侧 ShippingSessionSummaryPanel 为唯一状态与跳转面;纯 open_existing 时用重复关联文案。
|
||||
*/
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { CircleCheck, CircleX, LoaderCircle, TriangleAlert } from 'lucide-vue-next';
|
||||
import {
|
||||
listWorkspaceShippingOrderExtractionDocuments,
|
||||
listWorkspaceShippingOrderExtractionProgressEvents,
|
||||
} from '../../api/shipping.api';
|
||||
import type { ShippingOrderExtractionState } from '../../types/chat.types';
|
||||
import type {
|
||||
ShippingOrderExtractionDocumentResult,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
} from '../../types/shipping.api.types';
|
||||
import ShippingOrderExtractionDetailsDrawer from './ShippingOrderExtractionDetailsDrawer.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
state: ShippingOrderExtractionState;
|
||||
@@ -27,50 +17,25 @@ const props = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
retry: [];
|
||||
enterManualReview: [];
|
||||
}>();
|
||||
|
||||
const { t, te } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
|
||||
const detailsOpen = ref(false);
|
||||
const documents = ref<ShippingOrderExtractionDocumentResult[]>([]);
|
||||
const progressEvents = ref<ShippingOrderExtractionProgressEvent[]>([]);
|
||||
const loadingDocuments = ref(false);
|
||||
const documentsLoadFailed = ref(false);
|
||||
const documentsLoadedForRun = ref('');
|
||||
const loadingProgressEvents = ref(false);
|
||||
const progressEventsLoadFailed = ref(false);
|
||||
const progressEventsLoadedForRun = ref('');
|
||||
let detailsRefreshTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
const detailsFreshnessKey = computed(() => JSON.stringify({
|
||||
runNo: props.runNo || '',
|
||||
status: props.state.status,
|
||||
phase: props.state.currentActivity?.eventCode || '',
|
||||
total: props.state.summary.totalDocuments,
|
||||
completed: props.state.summary.completedDocuments,
|
||||
reviewRequired: props.state.summary.reviewRequiredDocuments,
|
||||
failed: props.state.summary.failedDocuments,
|
||||
}));
|
||||
|
||||
watch(
|
||||
() => props.runNo,
|
||||
() => {
|
||||
detailsOpen.value = false;
|
||||
documents.value = [];
|
||||
progressEvents.value = [];
|
||||
loadingDocuments.value = false;
|
||||
loadingProgressEvents.value = false;
|
||||
documentsLoadFailed.value = false;
|
||||
progressEventsLoadFailed.value = false;
|
||||
documentsLoadedForRun.value = '';
|
||||
progressEventsLoadedForRun.value = '';
|
||||
},
|
||||
);
|
||||
/**
|
||||
* 是否为「仅重复关联已有任务、无需人工复核」终态通知。
|
||||
*/
|
||||
const isDuplicateOnlyNotice = computed(() => {
|
||||
const opened = Math.max(0, Number(props.state.summary.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));
|
||||
return review === 0 && failed === 0;
|
||||
});
|
||||
|
||||
const toneClass = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return 'border-violet-200 bg-violet-50/80 text-violet-950 dark:border-violet-800 dark:bg-violet-950/35 dark:text-violet-100';
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return 'border-emerald-200 bg-emerald-50/80 text-emerald-950 dark:border-emerald-800 dark:bg-emerald-950/35 dark:text-emerald-100';
|
||||
@@ -85,272 +50,80 @@ const toneClass = computed(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const titleKey = computed(() => `chat.shippingOrderExtractionCardTitle.${props.state.status}`);
|
||||
/**
|
||||
* 一句过程通知;纯重复关联不误报「需人工处理」。
|
||||
*/
|
||||
const compactLine = computed(() => {
|
||||
if (isDuplicateOnlyNotice.value) {
|
||||
return t('chat.shippingSessionSummary.processNoticeDuplicateLinked');
|
||||
}
|
||||
switch (props.state.status) {
|
||||
case 'completed':
|
||||
return t('chat.shippingSessionSummary.processNoticeCompleted');
|
||||
case 'partially_completed':
|
||||
case 'review_required':
|
||||
return t('chat.shippingSessionSummary.processNoticeNeedsAction');
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
return t('chat.shippingSessionSummary.processNoticeFailed');
|
||||
default:
|
||||
return t('chat.shippingSessionSummary.processNoticeProcessing');
|
||||
}
|
||||
});
|
||||
|
||||
const activityKey = computed(() => {
|
||||
const code = String(props.state.currentActivity?.eventCode || '').trim();
|
||||
const key = `chat.shippingOrderExtractionActivity.${code}`;
|
||||
return code && te(key) ? key : 'chat.shippingOrderExtractionActivity.generic_processing';
|
||||
});
|
||||
const completedLabel = computed(() => `${props.state.summary.completedDocuments} / ${props.state.summary.totalDocuments}`);
|
||||
const selectionSummaryItems = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
const unitSummary = props.state.unitSummary;
|
||||
return [
|
||||
selectionPlan?.selectedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSelected', { count: selectionPlan.selectedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.pendingExpansionAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanPendingExpansion', { count: selectionPlan.pendingExpansionAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.skippedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanSkipped', { count: selectionPlan.skippedAttachmentCount })
|
||||
: '',
|
||||
selectionPlan?.budgetLimitedAttachmentCount
|
||||
? t('chat.shippingOrderExtractionPlanBudgetLimited', { count: selectionPlan.budgetLimitedAttachmentCount })
|
||||
: '',
|
||||
unitSummary?.retryingUnits
|
||||
? t('chat.shippingOrderExtractionPlanRetrying', { count: unitSummary.retryingUnits })
|
||||
: '',
|
||||
unitSummary?.failedUnits
|
||||
? t('chat.shippingOrderExtractionPlanTechnicalFailures', { count: unitSummary.failedUnits })
|
||||
: '',
|
||||
].filter(Boolean);
|
||||
});
|
||||
const selectionPlanHint = computed(() => {
|
||||
const selectionPlan = props.state.selectionPlan;
|
||||
if (!selectionPlan?.totalAttachmentCount) return '';
|
||||
return t('chat.shippingOrderExtractionPlanSummary', {
|
||||
total: selectionPlan.totalAttachmentCount,
|
||||
groups: selectionPlan.groupCount || 0,
|
||||
attachments: selectionPlan.maxInitialAttachments || 0,
|
||||
concurrency: selectionPlan.maxInitialConcurrency || 0,
|
||||
});
|
||||
return code && te(key) ? key : '';
|
||||
});
|
||||
|
||||
const translateReasonCodes = (codes: string[] | undefined): string[] => (
|
||||
(codes || [])
|
||||
.map((code) => {
|
||||
const normalized = String(code || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderExtractionReason.${normalized}`;
|
||||
return te(key) ? t(key) : normalized;
|
||||
})
|
||||
.filter(Boolean)
|
||||
);
|
||||
|
||||
const reviewReasonSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.reviewRequiredReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionReviewReasonCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const expansionTriggerSummary = computed(() => {
|
||||
const labels = translateReasonCodes(props.state.unitSummary?.expansionTriggerReasonCodes);
|
||||
return labels.length
|
||||
? t('chat.shippingOrderExtractionExpansionTriggerCodes', { codes: labels.join(' / ') })
|
||||
: '';
|
||||
});
|
||||
|
||||
const currentActivityContextSummary = computed(() => {
|
||||
const parts: string[] = [];
|
||||
const batch = Number(props.state.currentActivity?.selectionBatch || 0);
|
||||
if (batch > 0) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivitySelectionBatch', { batch }));
|
||||
}
|
||||
const labels = translateReasonCodes(props.state.currentActivity?.reasonCodes);
|
||||
if (labels.length) {
|
||||
parts.push(t('chat.shippingOrderExtractionActivityReasonCodes', { codes: labels.join(' / ') }));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
});
|
||||
|
||||
/**
|
||||
* 刷新抽屉中的 Run 详情。
|
||||
*
|
||||
* 文档列表可能在布局 Job 完成后才落库;抽屉绝不能缓存首次打开时的空结果,
|
||||
* 否则聊天卡已显示新状态而详情仍停留在旧的“暂无结果”。
|
||||
*/
|
||||
const refreshDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
const tasks: Promise<void>[] = [];
|
||||
if (!loadingDocuments.value) {
|
||||
loadingDocuments.value = true;
|
||||
documentsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionDocuments(props.runNo)
|
||||
.then((response) => {
|
||||
documents.value = response.items;
|
||||
documentsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
documentsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingDocuments.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!loadingProgressEvents.value) {
|
||||
loadingProgressEvents.value = true;
|
||||
progressEventsLoadFailed.value = false;
|
||||
tasks.push(
|
||||
listWorkspaceShippingOrderExtractionProgressEvents(props.runNo)
|
||||
.then((response) => {
|
||||
progressEvents.value = response.items;
|
||||
progressEventsLoadedForRun.value = props.runNo || '';
|
||||
})
|
||||
.catch(() => {
|
||||
progressEventsLoadFailed.value = true;
|
||||
})
|
||||
.finally(() => {
|
||||
loadingProgressEvents.value = false;
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (tasks.length) {
|
||||
await Promise.all(tasks);
|
||||
}
|
||||
};
|
||||
|
||||
const openDetails = async () => {
|
||||
if (!props.runNo) return;
|
||||
detailsOpen.value = true;
|
||||
await refreshDetails();
|
||||
};
|
||||
|
||||
/** 详情打开期间独立刷新,避免长任务只在聊天卡状态变更时才显示新阶段。 */
|
||||
const stopDetailsRefresh = () => {
|
||||
if (detailsRefreshTimer) clearInterval(detailsRefreshTimer);
|
||||
detailsRefreshTimer = null;
|
||||
};
|
||||
|
||||
watch(detailsOpen, (open) => {
|
||||
stopDetailsRefresh();
|
||||
if (!open || !props.runNo || !['queued', 'processing'].includes(props.state.status)) return;
|
||||
detailsRefreshTimer = setInterval(() => void refreshDetails(), 2000);
|
||||
});
|
||||
|
||||
watch(() => props.state.status, (status) => {
|
||||
if (!['queued', 'processing'].includes(status)) stopDetailsRefresh();
|
||||
});
|
||||
|
||||
onBeforeUnmount(stopDetailsRefresh);
|
||||
|
||||
watch(detailsFreshnessKey, () => {
|
||||
if (detailsOpen.value) void refreshDetails();
|
||||
});
|
||||
|
||||
/** 新建单前复核统一进入独立工作台,不能再落入聊天内旧 Candidate 编辑区。 */
|
||||
const openReviewWorkspace = async () => {
|
||||
if (!props.runNo) return;
|
||||
await router.push({
|
||||
name: 'Chat',
|
||||
params: { agentId: String(route.params.agentId || '') },
|
||||
query: {
|
||||
...route.query,
|
||||
mode: 'order-review',
|
||||
run_no: props.runNo,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleActionClick = async (action: string) => {
|
||||
switch (action) {
|
||||
case 'view_details':
|
||||
await openDetails();
|
||||
return;
|
||||
case 'enter_manual_review':
|
||||
await openReviewWorkspace();
|
||||
return;
|
||||
case 'retry_failed_attachments':
|
||||
emit('retry');
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
const showRetry = computed(() => (
|
||||
props.state.availableActions.includes('retry_failed_attachments')
|
||||
|| props.state.summary.failedDocuments > 0
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mb-3 rounded-lg border px-3.5 py-3" :class="toneClass">
|
||||
<div
|
||||
class="mb-3 rounded-lg border px-3.5 py-2.5"
|
||||
:class="toneClass"
|
||||
data-testid="shipping-order-extraction-card"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<LoaderCircle
|
||||
v-if="state.status === 'queued' || state.status === 'processing'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0 animate-spin"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 animate-spin"
|
||||
/>
|
||||
<CircleCheck
|
||||
v-else-if="state.status === 'completed' || isDuplicateOnlyNotice"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleCheck v-else-if="state.status === 'completed'" class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<TriangleAlert
|
||||
v-else-if="state.status === 'partially_completed' || state.status === 'review_required'"
|
||||
class="mt-0.5 h-5 w-5 shrink-0"
|
||||
class="mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<CircleX v-else class="mt-0.5 h-5 w-5 shrink-0" />
|
||||
<CircleX v-else class="mt-0.5 h-4 w-4 shrink-0" />
|
||||
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-sm font-semibold">{{ t(titleKey) }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs opacity-90">
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.total', { count: state.summary.totalDocuments }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.completedProgress', { value: completedLabel }) }}</span>
|
||||
<span>{{ t('chat.shippingOrderExtractionSummary.reviewRequired', { count: state.summary.reviewRequiredDocuments }) }}</span>
|
||||
<span v-if="state.summary.failedDocuments > 0">
|
||||
{{ t('chat.shippingOrderExtractionSummary.failed', { count: state.summary.failedDocuments }) }}
|
||||
</span>
|
||||
<div class="text-sm font-medium">{{ compactLine }}</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-1 text-xs opacity-80">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', {
|
||||
fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument'),
|
||||
}) }}
|
||||
<span v-if="activityKey"> · {{ t(activityKey) }}</span>
|
||||
</div>
|
||||
<div v-if="state.currentActivity?.fileName" class="mt-2 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionCurrentFile', { fileName: state.currentActivity.fileName || t('chat.shippingOrderExtractionUnknownDocument') }) }}
|
||||
</div>
|
||||
<div v-if="state.currentActivity" class="mt-1 text-xs opacity-80">
|
||||
{{ t(activityKey) }}
|
||||
</div>
|
||||
<div v-if="currentActivityContextSummary" class="mt-1 text-xs opacity-80">
|
||||
{{ currentActivityContextSummary }}
|
||||
</div>
|
||||
<div v-if="selectionPlanHint" class="mt-2 text-xs opacity-85">
|
||||
{{ selectionPlanHint }}
|
||||
</div>
|
||||
<div v-if="reviewReasonSummary" class="mt-2 text-xs opacity-85">
|
||||
{{ reviewReasonSummary }}
|
||||
</div>
|
||||
<div v-if="expansionTriggerSummary" class="mt-1 text-xs opacity-85">
|
||||
{{ expansionTriggerSummary }}
|
||||
</div>
|
||||
<div v-if="selectionSummaryItems.length" class="mt-2 flex flex-wrap gap-2 text-[11px] font-medium opacity-90">
|
||||
<span
|
||||
v-for="item in selectionSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-full bg-black/10 px-2 py-0.5 dark:bg-white/10"
|
||||
>
|
||||
{{ item }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="state.refreshFailed" class="mt-2 text-xs font-medium opacity-90">
|
||||
<div v-if="state.refreshFailed" class="mt-1 text-xs font-medium opacity-90">
|
||||
{{ t('chat.shippingOrderExtractionRefreshFailed') }}
|
||||
</div>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="action in state.availableActions"
|
||||
:key="action"
|
||||
type="button"
|
||||
class="inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="handleActionClick(action)"
|
||||
>
|
||||
{{ t(`chat.shippingOrderExtractionAction.${action}`) }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-if="showRetry"
|
||||
type="button"
|
||||
class="mt-2 inline-flex items-center rounded-md border border-current/20 px-2.5 py-1 text-xs font-medium hover:bg-black/5 dark:hover:bg-white/5"
|
||||
@click="emit('retry')"
|
||||
>
|
||||
{{ t('chat.shippingOrderExtractionAction.retry_failed_attachments') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingOrderExtractionDetailsDrawer
|
||||
:open="detailsOpen"
|
||||
:state="state"
|
||||
:documents="documents"
|
||||
:progress-events="progressEvents"
|
||||
:loading="loadingDocuments"
|
||||
:load-failed="documentsLoadFailed"
|
||||
:progress-loading="loadingProgressEvents"
|
||||
:progress-load-failed="progressEventsLoadFailed"
|
||||
@close="detailsOpen = false"
|
||||
@enter-manual-review="openReviewWorkspace"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
Reference in new issue
Block a user