447 lines
19 KiB
TypeScript
447 lines
19 KiB
TypeScript
/**
|
||
* features/chat/shipping/useChatShippingSendHandler.ts
|
||
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本、列映射和附件自动流程。
|
||
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
|
||
* 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。
|
||
*/
|
||
import {
|
||
getWorkspaceShippingBatch,
|
||
getWorkspaceShippingTask,
|
||
} from '@/features/chat/api/shipping.api';
|
||
import { SHIPPING_DECISION_ACTIONS, SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
|
||
import { buildShippingApplyMappingTurn, buildShippingSwitchFocusTurn } from './shippingTurnActions';
|
||
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 { createChatMessageAttachmentSnapshots } from '../utils/attachmentCard.utils';
|
||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||
import type { 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<boolean>;
|
||
isThinking: Ref<boolean>;
|
||
isUploadingAttachments: Ref<boolean>;
|
||
messages: Ref<ChatMessage[]>;
|
||
conversationId: Ref<string | null>;
|
||
history: Ref<ChatSessionItem[]>;
|
||
input: Ref<string>;
|
||
attachments: Ref<PendingAttachment[]>;
|
||
shippingAutoFlowRequested: Ref<boolean>;
|
||
resolvedShippingTaskId: Ref<string>;
|
||
getActiveShippingBatchNo: () => string;
|
||
currentAgentId: ComputedRef<number>;
|
||
selectedKb: Ref<string>;
|
||
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_intake_nos?: string[]; display_query?: string },
|
||
hooks?: SendMessageLifecycleHooks,
|
||
) => Promise<boolean | void>;
|
||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||
loadHistory: () => Promise<void>;
|
||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
||
openShippingInventoryPicker: () => boolean;
|
||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||
handleShippingMenuAction: (action: ShippingActionButton | { id?: string; message: string; label?: string; source_code?: string }) => Promise<void>;
|
||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
|
||
isShippingNoticeBatchSubmitting?: () => boolean;
|
||
hasBlockingNoticeIntake?: () => boolean;
|
||
hasNoticeIntakeFailures?: () => boolean;
|
||
hasBlockingNoticeDuplicates?: () => boolean;
|
||
hasCandidateReviewIssues?: () => boolean;
|
||
hasSelectedNoticeCandidates?: () => boolean;
|
||
openShippingDuplicateDialog?: (attachmentId?: string) => void;
|
||
getParsedIntakeNos?: () => string[];
|
||
markOrderExtractionStarted?: (intakeNos: string[]) => void;
|
||
rollbackOrderExtractionStarted?: (intakeNos: string[]) => void;
|
||
refreshNoticeIntakeStatuses?: () => Promise<void>;
|
||
clearConsumedNoticeAttachments?: () => void;
|
||
applyShippingMessageRecovery?: (message: ChatMessage) => Promise<boolean>;
|
||
applyShippingBatchSnapshot?: (message: ChatMessage) => boolean;
|
||
syncShippingConversationWorkspace: (options?: { preferLatest?: boolean }) => Promise<boolean>;
|
||
refreshShippingActions: () => Promise<void>;
|
||
shippingSuggestedPrompt: ComputedRef<string>;
|
||
isShippingShortageQueryIntent: (text: string) => boolean;
|
||
queryShippingShortageDetails: (taskNo?: string, displayText?: string) => Promise<boolean>;
|
||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||
t: (key: string, ...args: unknown[]) => string;
|
||
}
|
||
|
||
/**
|
||
* 创建发货通知发送拦截器。
|
||
*
|
||
* 核心逻辑:已预处理邮件固定 Intake 上下文后调用普通聊天;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。
|
||
* @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<boolean> => {
|
||
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<boolean> => {
|
||
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<boolean> => {
|
||
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 userAttachments = createChatMessageAttachmentSnapshots(noticeItems);
|
||
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
|
||
ctx.shippingAutoFlowRequested.value = false;
|
||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||
ctx.markOrderExtractionStarted?.(intakeNos);
|
||
try {
|
||
const sent = await ctx.sendMessage(
|
||
query,
|
||
ctx.currentAgentId.value,
|
||
ctx.selectedKb.value,
|
||
[],
|
||
{
|
||
shipping_intake_nos: intakeNos,
|
||
display_query: query,
|
||
},
|
||
{
|
||
userAttachments,
|
||
onAssistantMessageFinished: async (assistantMessage) => {
|
||
if (ctx.applyShippingMessageRecovery) {
|
||
await ctx.applyShippingMessageRecovery(assistantMessage);
|
||
} else {
|
||
ctx.applyShippingBatchSnapshot?.(assistantMessage);
|
||
}
|
||
await ctx.refreshNoticeIntakeStatuses?.();
|
||
if (!(await ctx.syncShippingConversationWorkspace({ preferLatest: true }))) {
|
||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||
await ctx.syncShippingConversationWorkspace({ preferLatest: true });
|
||
}
|
||
ctx.clearConsumedNoticeAttachments?.();
|
||
await ctx.refreshShippingActions();
|
||
},
|
||
},
|
||
);
|
||
if (sent === false) {
|
||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||
return true;
|
||
}
|
||
await ctx.loadHistory();
|
||
} catch (e: unknown) {
|
||
ctx.rollbackOrderExtractionStarted?.(intakeNos);
|
||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||
ctx.msg.warning(errorMessage);
|
||
}
|
||
return true;
|
||
}
|
||
}
|
||
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;
|
||
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<Extract<PendingAttachment, { kind: 'local' }>>;
|
||
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 {
|
||
await ctx.handleShippingAutoUploadFile(first.file);
|
||
} catch (e: unknown) {
|
||
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
|
||
ctx.msg.warning(errorMessage);
|
||
}
|
||
return true;
|
||
}
|
||
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<boolean> => {
|
||
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 (menuChoice === 'paste') {
|
||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||
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 (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 = [];
|
||
const turn = buildShippingApplyMappingTurn(taskId, mapping);
|
||
await ctx.startChatTurn({
|
||
agentId: ctx.currentAgentId.value,
|
||
inputType: 'form_submit',
|
||
displayText: `${content.trim()}\n任务编号:${taskId}`,
|
||
actionType: turn.actionType,
|
||
payload: turn.payload,
|
||
refs: turn.refs,
|
||
hooks: {
|
||
onAssistantMessageFinished: async () => {
|
||
void ctx.refreshShippingActions();
|
||
},
|
||
},
|
||
});
|
||
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.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 };
|
||
}
|