/** * features/chat/shipping/useChatShippingSendHandler.ts * 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。 * 依赖:shipping.api、shippingIntents、shippingMenu、shippingDownload、chat.types。 * 逻辑:已预处理 Intake 创建独立订单抽取 Run;其他业务动作经 Chat Turn / handleShippingMenuAction。 */ import { getWorkspaceShippingBatch, getWorkspaceShippingTask, } from '@/features/chat/api/shipping.api'; import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping'; import { buildShippingSwitchFocusTurn } from './shippingTurnActions'; import { downloadWorkspaceShippingExcelFile } from './shippingDownload'; import { isShippingDownloadExcelIntent, isShippingGenerateExcelIntent, isShippingInventoryUploadIntent, isShippingManualUploadIntent, parseShippingTaskSwitchIntent, } from './shippingIntents'; import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu'; import { isShippingSpreadsheetFile, isTemporaryInventoryDeclaration } from './shippingUploadPrompt'; import { extractExt } from '../constants/shipping'; import { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils'; import type { SendMessageLifecycleHooks } from '../composables/useChat'; import type { ChatMessageSendResult, StartChatTurnOptions } from '../types/chat-turn.types'; import type { ChatMessage, ChatSessionItem } from '../types/chat.types'; import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types'; import type { ComputedRef, Ref } from 'vue'; export interface ShippingSendHandlerContext { isShippingNoticeAgent: ComputedRef; isThinking: Ref; isUploadingAttachments: Ref; messages: Ref; conversationId: Ref; history: Ref; input: Ref; attachments: Ref; shippingAutoFlowRequested: Ref; resolvedShippingTaskId: Ref; getActiveShippingBatchNo: () => string; currentAgentId: ComputedRef; selectedKb: Ref; attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>; getActiveShippingTaskId: () => string; lastAssistantMessageContent: () => string; lastAssistantShippingActions: () => ChatMessage['shipping_actions']; sendMessage: ( content: string, agentId: number, kb: string, files: ChatUploadFileSpec[], context?: { task_id?: string; batch_no?: string; shipping_temporary_inventory_asset_no?: string; shipping_temporary_inventory_session_no?: string; display_query?: string }, hooks?: SendMessageLifecycleHooks, ) => Promise; buildFileSpecsForSend: () => Promise; loadHistory: () => Promise; sendShippingMenuMessage: (message: string) => Promise; startChatTurn: (options: StartChatTurnOptions) => Promise; openShippingInventoryPicker: () => boolean; executeShippingDecision: (decision: string, displayText?: string) => Promise; executeShippingManualUpload: (taskId: string, displayText?: string) => Promise; handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise; handleShippingAutoUploadFile: (file: File) => Promise; handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise; isShippingNoticeBatchSubmitting?: () => boolean; hasBlockingNoticeIntake?: () => boolean; hasNoticeIntakeFailures?: () => boolean; hasBlockingNoticeDuplicates?: () => boolean; hasCandidateReviewIssues?: () => boolean; hasSelectedNoticeCandidates?: () => boolean; openShippingDuplicateDialog?: (attachmentId?: string) => void; getParsedIntakeNos?: () => string[]; startOrderExtractionRun?: ( query: string, intakeNos: string[], attachments: ReturnType, uploadBatchId?: string, ) => Promise; applyShippingMessageRecovery?: (message: ChatMessage) => Promise; applyShippingBatchSnapshot?: (message: ChatMessage) => boolean; syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise; refreshShippingActions: () => Promise; shippingSuggestedPrompt: ComputedRef; isShippingShortageQueryIntent: (text: string) => boolean; queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise; msg: { warning: (text: string) => void; info: (text: string) => void }; t: (key: string, ...args: unknown[]) => string; } /** * 创建发货通知发送拦截器。 * * 核心逻辑:已预处理邮件固定 Intake 后创建后台 Run;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。 * @param ctx - 发送拦截上下文 * @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送 */ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { const normalizeInventorySourceText = (value: string) => String(value || '') .toUpperCase() .replace(/[^A-Z0-9]+/g, ''); const tryConfirmInventorySourceFromText = async (content: string): Promise => { const taskId = ctx.getActiveShippingTaskId(); if (!taskId) return false; const normalized = normalizeInventorySourceText(content); if (!normalized) return false; try { const detail = await getWorkspaceShippingTask(taskId); if (detail.pending_human_reason !== 'inventory_source_unresolved') return false; const resolution = detail.inventory_source_resolution; const candidates = resolution && typeof resolution === 'object' ? (resolution as { candidates?: unknown }).candidates : null; if (!Array.isArray(candidates) || candidates.length === 0) return false; const hit = candidates.find((item) => { if (!item || typeof item !== 'object') return false; const source = item as { source_code?: unknown; display_name?: unknown; warehouse_code?: unknown; program_name?: unknown }; const values = [ source.source_code, source.display_name, source.warehouse_code, source.program_name, ].map((value) => normalizeInventorySourceText(String(value || ''))).filter(Boolean); return values.some((value) => normalized === value || normalized.includes(value) || value.includes(normalized)); }) as { source_code?: unknown; display_name?: unknown } | undefined; const sourceCode = String(hit?.source_code || '').trim().toUpperCase(); if (!sourceCode) return false; if (typeof content !== 'string') return false; ctx.input.value = ''; ctx.attachments.value = []; const label = String(hit?.display_name || sourceCode).trim(); await ctx.handleShippingMenuAction({ id: 'confirm_inventory_source', message: ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label }), label, source_code: sourceCode, }); return true; } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUi.inventorySource.confirmFailed'); ctx.msg.warning(errorMessage); return true; } }; const trySwitchShippingTask = async (content: string): Promise => { const intent = parseShippingTaskSwitchIntent(content); if (!intent) return false; const batchNo = ctx.getActiveShippingBatchNo(); if (!batchNo) { ctx.msg.warning('当前没有可切换的批次'); return true; } try { const detail = await getWorkspaceShippingBatch(batchNo); const tasks = Array.isArray(detail.tasks) ? detail.tasks : []; if (tasks.length <= 1) { ctx.msg.info('当前批次只有 1 票,无需切换'); return true; } const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase(); const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0); let targetTaskNo = ''; if (intent.mode === 'task') { targetTaskNo = String(intent.taskNo || '').trim().toUpperCase(); } else if (intent.mode === 'next') { targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase(); } else { targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase(); } if (!targetTaskNo) { ctx.msg.warning('未找到要切换的任务'); return true; } if (targetTaskNo === focusTaskNo) { ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务'); return true; } ctx.resolvedShippingTaskId.value = targetTaskNo; const turn = buildShippingSwitchFocusTurn(batchNo, targetTaskNo, content.trim()); await ctx.startChatTurn({ agentId: ctx.currentAgentId.value, inputType: 'action', displayText: turn.displayText, actionType: turn.actionType, payload: turn.payload, refs: turn.refs, hooks: { onAssistantMessageFinished: async () => { void ctx.refreshShippingActions(); }, }, }); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '切换任务失败'; ctx.msg.warning(errorMessage); } return true; }; const tryHandleShippingAttachmentAutoFlow = async ( textOrEvent: string | Event | undefined, _content: string, trimmed: string, ): Promise => { if (!ctx.isShippingNoticeAgent.value) return false; const noticeItems = ctx.attachments.value.filter((item) => item.kind === 'shipping_notice'); if (noticeItems.length > 0) { if (ctx.hasBlockingNoticeIntake?.()) { ctx.msg.info(ctx.t('chat.shippingNoticeWaitingForParse')); return true; } if (ctx.hasNoticeIntakeFailures?.()) { ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint')); return true; } const intakeNos = ctx.getParsedIntakeNos?.() || []; if (intakeNos.length) { const submittedIntakes = new Set(intakeNos.map((item) => item.trim().toUpperCase())); const batchIds = new Set( noticeItems .filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase())) .map((item) => String(item.uploadBatchId || '').trim()) .filter(Boolean), ); if (batchIds.size > 1) { ctx.msg.warning('当前发送批次不一致,请重新上传需要一起识别的文件'); return true; } const userAttachments = createChatMessageAttachmentSnapshots( noticeItems.filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase()), ), ); // 阶段 2:发送是“授权开始识别”,备注允许为空,不能再偷偷注入默认提示词。 const query = trimmed; ctx.shippingAutoFlowRequested.value = false; if (typeof textOrEvent !== 'string') ctx.input.value = ''; try { const uploadBatchId = [...batchIds][0]; const started = uploadBatchId ? await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments, uploadBatchId) : await ctx.startOrderExtractionRun?.(query, intakeNos, userAttachments); if (!started) return true; ctx.attachments.value = ctx.attachments.value.filter( (item) => item.kind !== 'shipping_notice' || !item.intakeNo || !submittedIntakes.has(item.intakeNo.trim().toUpperCase()), ); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '文件处理失败'; ctx.msg.warning(errorMessage); } return true; } } if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false; if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false; if (ctx.isShippingNoticeBatchSubmitting?.()) { ctx.msg.info(ctx.t('chat.shippingNoticeBatchSubmitting')); return true; } const requestedAutoFlow = ctx.shippingAutoFlowRequested.value; ctx.shippingAutoFlowRequested.value = false; const localFiles = ctx.attachments.value.filter((a) => a.kind === 'local') as Array>; const first = localFiles[0]; if (!first) { ctx.msg.warning('当前仅支持本地附件触发自动流程'); return true; } if (isShippingSpreadsheetFile(first.file, extractExt)) { if (!isTemporaryInventoryDeclaration(trimmed)) { // 仅附件或自动建议时必须先澄清;有其他明确文本则交回普通对话,不把表格擅自归类。 if (!trimmed || requestedAutoFlow) { ctx.msg.info(ctx.t('chat.shippingNoticeSpreadsheetIntentRequired')); return true; } return false; } ctx.attachments.value = []; if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (localFiles.length > 1) { ctx.msg.warning('一次仅支持处理一个文件,将自动处理第一个'); } try { await ctx.handleShippingAutoUploadFile(first.file); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '文件处理失败'; ctx.msg.warning(errorMessage); } return true; } if (!(ctx.shippingAutoFlowRequested.value || !trimmed)) return false; if (!trimmed || requestedAutoFlow) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; try { await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file)); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '文件处理失败'; ctx.msg.warning(errorMessage); } return true; } return false; }; const tryHandleShippingSend = async ( textOrEvent: string | Event | undefined, content: string, _trimmed: string, ): Promise => { if (!ctx.isShippingNoticeAgent.value) return false; if (ctx.isShippingShortageQueryIntent(content)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; return ctx.queryShippingShortageDetails(undefined, content.trim()); } if (await trySwitchShippingTask(content)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; return true; } if (await tryConfirmInventorySourceFromText(content)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; return true; } const assistantCtx = ctx.lastAssistantMessageContent(); const numericText = content.trim(); if (/^[1-91-9](?:[\.\、\)::]?)$/.test(numericText)) { const num = Number.isFinite(Number(numericText.charAt(0))) ? Number(numericText.charAt(0)) : '0123456789'.indexOf(numericText.charAt(0)); const actions = ctx.lastAssistantShippingActions() || []; const action = num >= 1 ? actions[num - 1] : undefined; if (action) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; await ctx.handleShippingMenuAction(action); return true; } } const menuChoice = resolveShippingNumericChoice(content, assistantCtx); if (menuChoice) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (menuChoice === 'upload') { if (ctx.openShippingInventoryPicker()) return true; } else if (SHIPPING_DECISION_ACTIONS.has(menuChoice)) { const spec = SHIPPING_MENU_ACTION_SPECS[menuChoice]; await ctx.executeShippingDecision(menuChoice, spec?.label || spec?.message || menuChoice); return true; } else { await ctx.sendShippingMenuMessage(SHIPPING_MENU_ACTION_SPECS[menuChoice].message); return true; } } const shippingDecision = resolveShippingDecisionFromText(content, assistantCtx); if (shippingDecision) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (await ctx.executeShippingDecision(shippingDecision, content.trim())) return true; } if (isShippingManualUploadIntent(content)) { const taskId = ctx.getActiveShippingTaskId(); if (!taskId) { ctx.msg.warning('未找到任务编号,请先完成前面的步骤'); return true; } ctx.resolvedShippingTaskId.value = taskId; if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; await ctx.executeShippingManualUpload(taskId, content.trim()); return true; } if (isShippingInventoryUploadIntent(content, assistantCtx)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (ctx.openShippingInventoryPicker()) return true; return true; } if (isShippingGenerateExcelIntent(content)) { const taskId = ctx.getActiveShippingTaskId(); if (!taskId) { ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配'); return true; } ctx.resolvedShippingTaskId.value = taskId; if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; await ctx.handleShippingMenuAction({ id: 'generate_excel', message: content.trim() }); return true; } if (isShippingDownloadExcelIntent(content)) { const taskId = ctx.getActiveShippingTaskId(); if (!taskId) { ctx.msg.warning('未找到任务编号,请先完成解析与库存匹配'); return true; } ctx.resolvedShippingTaskId.value = taskId; if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; try { await downloadWorkspaceShippingExcelFile(taskId); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '下载 Excel 失败'; ctx.msg.warning(errorMessage); } return true; } return false; }; return { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow }; }