/** * features/chat/shipping/useChatShippingSendHandler.ts * 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本和附件自动流程。 * 依赖:shipping.api(任务详情)、shippingIntents、shippingMenu、shippingDownload、chat.types。 * 逻辑:已预处理 Intake 创建独立订单抽取 Run;co8 后切票不再调用 shipping_batches API,改提示用户使用 processing 工作台。 */ import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping'; import { downloadWorkspaceShippingExcelFile } from './shippingDownload'; import { isShippingDownloadExcelIntent, isShippingGenerateExcelIntent, isShippingManualUploadIntent, parseShippingTaskSwitchIntent, } from './shippingIntents'; import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu'; import { isShippingSpreadsheetFile, isTemporaryInventoryDeclaration } from './shippingUploadPrompt'; import { extractExt } from '../constants/shipping'; import { CHAT_USER_ATTACHMENT_LIMIT, 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; 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; 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; 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; 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) { /** * 拦截切票/切任务意图(co8 已下线批次 API)。 * * 核心逻辑:识别切换意图后提示用户使用右侧 processing 工作台,消费发送且不发起网络请求。 * @param content - 用户输入 * @returns 识别到切换意图时恒为 true */ const trySwitchShippingTask = async (content: string): Promise => { const intent = parseShippingTaskSwitchIntent(content); if (!intent) return false; ctx.msg.warning(ctx.t('chat.shippingNoticeUi.batchSwitchRemoved')); return true; }; /** * 拦截发货通知附件自动流程(订单抽取、本地表格/邮件入队)。 * * 核心逻辑:已解析 Intake 走 startOrderExtractionRun;快照数超 CHAT_USER_ATTACHMENT_LIMIT 时 warning 并消费发送。 * @param textOrEvent - 发送触发源(按钮或文本) * @param _content - 原始输入(保留供后续分支) * @param trimmed - 去空白后的用户正文 * @returns 已消费本次发送时为 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), ); const userAttachments = createChatMessageAttachmentSnapshots( noticeItems.filter((item) => item.intakeNo && submittedIntakes.has(item.intakeNo.trim().toUpperCase()), ), ); if (userAttachments.length > CHAT_USER_ATTACHMENT_LIMIT) { ctx.msg.warning(ctx.t('chat.attachmentsUi.limitReached', { limit: CHAT_USER_ATTACHMENT_LIMIT })); return true; } // 空备注不伪造用户正文;订单抽取动作由结构化 Run 提交承载,用户消息只保留附件快照。 const query = trimmed; ctx.shippingAutoFlowRequested.value = false; if (typeof textOrEvent !== 'string') ctx.input.value = ''; try { // 多次文件选择可以共同进入一个 Run;仅单一上传批次时携带该幂等提示。 const uploadBatchId = batchIds.size === 1 ? [...batchIds][0] : undefined; 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) { // co8:本地文件改走 Intake 入队,不再清空后打 create_batch Chat Turn。 if (typeof textOrEvent !== 'string') ctx.input.value = ''; try { await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file)); ctx.attachments.value = ctx.attachments.value.filter((item) => item.kind !== 'local'); } 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; } 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 (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)) { ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench')); return true; } if (isShippingGenerateExcelIntent(content)) { ctx.msg.info(ctx.t('chat.shippingNoticeUi.manualUpload.openTaskWorkbench')); 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 }; }