/** * features/chat/shipping/useChatShippingSendHandler.ts * 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。 * 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。 * 逻辑:由 useChatShipping 调用本文件;本文件优先消费 shipping 领域意图,只有未命中时才放行到默认 Dify 对话链路。 */ import { applyWorkspaceShippingInventoryMapping, generateWorkspaceShippingExcel, getWorkspaceShippingBatch, switchWorkspaceShippingBatchFocusTask, } from '@/features/chat/api/shipping.api'; import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping'; import { buildShippingFieldAlignmentText } from './shippingMapping'; import { downloadWorkspaceShippingExcelFile } from './shippingDownload'; import { isShippingDownloadExcelIntent, isShippingGenerateExcelIntent, isShippingInventoryUploadIntent, isShippingManualUploadIntent, parseShippingTaskSwitchIntent, parseShippingColumnMappingFromText, } from './shippingIntents'; import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu'; import { classifyShippingUploadFile } from './shippingUploadPrompt'; import { extractExt } from '../constants/shipping'; import type { ChatMessage, ChatSessionItem } from '../types/chat.types'; import type { ChatUploadFileSpec, PendingAttachment } 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; sendMessage: ( content: string, agentId: number, kb: string, files: ChatUploadFileSpec[], ) => Promise; buildFileSpecsForSend: () => Promise; loadHistory: () => Promise; sendShippingMenuMessage: (message: string) => Promise; pushShippingLocalUserMessage: (text: string) => Promise; pushShippingLocalAssistantMessage: (text: string) => Promise; openShippingInventoryPicker: () => boolean; executeShippingDecision: (decision: string, displayText?: string) => Promise; executeShippingManualUpload: (taskId: string, displayText?: string) => Promise; handleShippingAutoUploadFile: (file: File) => Promise; handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise; refreshShippingActions: () => Promise; shippingSuggestedPrompt: ComputedRef; msg: { warning: (text: string) => void; info: (text: string) => void }; t: (key: string) => string; } /** * 创建发货通知发送拦截器。 * * 核心逻辑:识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图,并在命中时直接走本地前后端流程。 * @param ctx - 发送拦截上下文 * @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送 */ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) { 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; } await switchWorkspaceShippingBatchFocusTask(batchNo, targetTaskNo); ctx.resolvedShippingTaskId.value = targetTaskNo; await ctx.pushShippingLocalUserMessage(content.trim()); await ctx.pushShippingLocalAssistantMessage(`已切换到任务 ${targetTaskNo},请继续当前票处理。`); 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.shippingAutoFlowRequested.value || !trimmed)) return false; if (!ctx.isShippingNoticeAgent.value || ctx.attachments.value.length === 0) return false; if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false; 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; } const kind = classifyShippingUploadFile(first.file, extractExt); if (kind === 'inventory') { ctx.attachments.value = []; if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (localFiles.length > 1) { ctx.msg.warning('一次仅支持处理一个文件,将自动处理第一个'); } try { const prompt = trimmed || ctx.shippingSuggestedPrompt.value || '上传库存并进入字段对齐'; await ctx.pushShippingLocalUserMessage(prompt); await ctx.handleShippingAutoUploadFile(first.file); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '文件处理失败'; ctx.msg.warning(errorMessage); } return true; } if (!trimmed) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; try { const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务'; await ctx.pushShippingLocalUserMessage(prompt); 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 (await trySwitchShippingTask(content)) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; ctx.attachments.value = []; return true; } const assistantCtx = ctx.lastAssistantMessageContent(); const menuChoice = resolveShippingNumericChoice(content, assistantCtx); if (menuChoice) { if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (menuChoice === 'upload') { if (ctx.openShippingInventoryPicker()) return true; } else if (menuChoice === 'paste') { ctx.msg.info(ctx.t('chat.shippingNoticePasteHint')); 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 (assistantCtx.includes('schema_preview') || assistantCtx.includes('列映射') || assistantCtx.includes('字段对齐')) { const mapping = parseShippingColumnMappingFromText(content); if (mapping) { 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.pushShippingLocalUserMessage(content.trim()); try { const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping); const alignmentText = buildShippingFieldAlignmentText(result); const hint = alignmentText || String(result.message || '').trim(); await ctx.pushShippingLocalAssistantMessage( [ `映射已应用:${Object.entries(mapping).map(([k, v]) => `${k}=${v}`).join(',')}`, `任务编号:${taskId}`, hint, ].filter(Boolean).join('\n'), ); void ctx.refreshShippingActions(); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '应用映射失败'; ctx.msg.warning(errorMessage); } 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; } 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.pushShippingLocalUserMessage(content.trim()); try { const result = await generateWorkspaceShippingExcel(taskId); await ctx.pushShippingLocalAssistantMessage( [ String(result.message || '').trim() || '已生成发货 Excel', `任务编号:${taskId}`, ].filter(Boolean).join('\n'), ); void ctx.refreshShippingActions(); } catch (e: unknown) { const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败'; ctx.msg.warning(errorMessage); } 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 = []; await ctx.pushShippingLocalUserMessage(content.trim()); 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 }; }