254 lines
10 KiB
TypeScript
254 lines
10 KiB
TypeScript
/**
|
|
* features/chat/shipping/useChatShippingMenuHandler.ts
|
|
* 用途:分发聊天气泡动作按钮点击;业务动作统一走 Chat Turn SSE。
|
|
* 依赖:shippingTurnActions、shipping.api(只读 task 详情)、shippingDownload、chat.types。
|
|
* 逻辑:可映射为 action_type 的按钮走 startChatTurn;纯 UI(下载/选文件/表单)仍走本地行为。
|
|
*/
|
|
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
|
|
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
|
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
|
import { buildShippingTurnRefs, resolveShippingChatTurn } from './shippingTurnActions';
|
|
import type { StartChatTurnOptions } from '../types/chat-turn.types';
|
|
import type { ChatMessage } from '../types/chat.types';
|
|
import type { ShippingActionButton } from '../types/shipping.types';
|
|
import type { ComputedRef, Ref } from 'vue';
|
|
|
|
export interface ShippingMenuHandlerContext {
|
|
isThinking: Ref<boolean>;
|
|
currentAgentId: ComputedRef<number>;
|
|
getActiveShippingTaskId: () => string;
|
|
getActiveShippingBatchNo: () => string;
|
|
messages: Ref<ChatMessage[]>;
|
|
sendShippingMenuMessage: (message: string) => Promise<void>;
|
|
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
|
openShippingInventoryPicker: (taskId?: string) => boolean;
|
|
openShippingNoticePicker: (taskId?: string) => boolean;
|
|
executeShippingDecision: (
|
|
decision: string,
|
|
displayText?: string,
|
|
options?: { silent?: boolean; taskId?: string },
|
|
) => Promise<boolean>;
|
|
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
|
refreshShippingActions: () => Promise<void>;
|
|
startChatTurn: (options: StartChatTurnOptions) => Promise<boolean>;
|
|
msg: { warning: (text: string) => void; info: (text: string) => void };
|
|
t: (key: string, ...args: unknown[]) => string;
|
|
}
|
|
|
|
export interface HandleShippingMenuActionOptions {
|
|
taskId?: string;
|
|
}
|
|
|
|
/**
|
|
* 创建发货通知动作菜单处理器。
|
|
*/
|
|
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
|
const normalizeInventorySourceText = (value: string) =>
|
|
String(value || '')
|
|
.toUpperCase()
|
|
.replace(/[^A-Z0-9]+/g, '');
|
|
|
|
const recentInventorySourceHint = () => {
|
|
const parts: string[] = [];
|
|
for (let i = ctx.messages.value.length - 1; i >= 0 && parts.length < 6; i -= 1) {
|
|
const content = String(ctx.messages.value[i]?.content || '').trim();
|
|
if (content) parts.push(content);
|
|
}
|
|
return parts.join('\n');
|
|
};
|
|
|
|
const resolveInventorySourceCodeFromContext = async (taskId: string): Promise<string> => {
|
|
const detail = await getWorkspaceShippingTask(taskId);
|
|
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 '';
|
|
if (candidates.length === 1) {
|
|
const only = candidates[0];
|
|
return only && typeof only === 'object'
|
|
? String((only as { source_code?: unknown }).source_code || '').trim().toUpperCase()
|
|
: '';
|
|
}
|
|
const hint = normalizeInventorySourceText(recentInventorySourceHint());
|
|
if (!hint) return '';
|
|
const matches = candidates.filter((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) => hint.includes(value) || value.includes(hint));
|
|
});
|
|
if (matches.length !== 1) return '';
|
|
return String((matches[0] as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
|
};
|
|
|
|
const runShippingActionTurn = async (
|
|
action: ShippingActionButton | { id?: string; message: string; label?: string },
|
|
taskId: string,
|
|
extra?: { sourceCode?: string },
|
|
) => {
|
|
const actionId = String(action.id || '').trim();
|
|
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
|
|
if (!turnSpec) return false;
|
|
const displayBase = String(action.message || actionId || ctx.t('chat.shippingNoticeToast.actionFallback')).trim();
|
|
const displayText = actionId === 'confirm_inventory_source'
|
|
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmWithTask', { taskId })
|
|
: ctx.t('chat.shippingNoticeUi.inventorySource.actionWithTask', { message: displayBase, taskId });
|
|
await ctx.startChatTurn({
|
|
agentId: ctx.currentAgentId.value,
|
|
inputType: 'action',
|
|
displayText,
|
|
actionType: turnSpec.actionType,
|
|
payload: turnSpec.payload,
|
|
refs: buildShippingTurnRefs(taskId, ctx.getActiveShippingBatchNo()),
|
|
hooks: {
|
|
onAssistantMessageFinished: async () => {
|
|
void ctx.refreshShippingActions();
|
|
},
|
|
},
|
|
});
|
|
return true;
|
|
};
|
|
|
|
const handleShippingMenuAction = async (
|
|
action: ShippingActionButton | { id?: string; message: string },
|
|
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
|
options?: HandleShippingMenuActionOptions,
|
|
) => {
|
|
const explicitTaskId = String(options?.taskId || '').trim().toUpperCase();
|
|
const resolveTaskId = () => explicitTaskId || ctx.getActiveShippingTaskId();
|
|
if (ctx.isThinking.value) return;
|
|
|
|
if (action.id === 'refresh') {
|
|
await ctx.refreshShippingActions();
|
|
ctx.msg.info(ctx.t('chat.shippingNoticeRefreshDone'));
|
|
return;
|
|
}
|
|
if (action.id === 'download_excel') {
|
|
const taskId = resolveTaskId();
|
|
if (!taskId) {
|
|
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
|
return;
|
|
}
|
|
try {
|
|
await downloadWorkspaceShippingExcelFile(taskId);
|
|
} catch (e: unknown) {
|
|
ctx.msg.warning(e instanceof Error ? e.message : ctx.t('chat.shippingNoticeToast.downloadExcelFailed'));
|
|
}
|
|
return;
|
|
}
|
|
|
|
const chatTurnActionIds = new Set([
|
|
'generate_excel',
|
|
'retry_upload',
|
|
'match_inventory',
|
|
'mark_manual_uploaded',
|
|
'confirm_inventory_source',
|
|
]);
|
|
|
|
if (action.id && chatTurnActionIds.has(action.id)) {
|
|
if (chatMsg?.shipping_actions_used) return;
|
|
if (chatMsg) chatMsg.shipping_actions_used = true;
|
|
const taskId = resolveTaskId();
|
|
if (!taskId) {
|
|
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
|
if (chatMsg) chatMsg.shipping_actions_used = false;
|
|
return;
|
|
}
|
|
try {
|
|
let sourceCode = '';
|
|
if (action.id === 'confirm_inventory_source') {
|
|
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
|
|
if (!sourceCode) {
|
|
sourceCode = await resolveInventorySourceCodeFromContext(taskId);
|
|
}
|
|
if (!sourceCode) {
|
|
ctx.msg.warning(ctx.t('chat.shippingNoticeUi.inventorySource.inputHint'));
|
|
if (chatMsg) chatMsg.shipping_actions_used = false;
|
|
return;
|
|
}
|
|
}
|
|
if (action.id === 'mark_manual_uploaded') {
|
|
await ctx.executeShippingManualUpload(taskId, ctx.t('chat.shippingNoticeToast.manualUploadedDefault'));
|
|
return;
|
|
}
|
|
const label = String(('label' in action ? action.label : '') || sourceCode).trim();
|
|
const displayMessage = action.id === 'confirm_inventory_source'
|
|
? ctx.t('chat.shippingNoticeUi.inventorySource.confirmDisplay', { label: label || sourceCode })
|
|
: action.message;
|
|
await runShippingActionTurn(
|
|
{ ...action, message: displayMessage },
|
|
taskId,
|
|
sourceCode ? { sourceCode } : undefined,
|
|
);
|
|
} catch (e: unknown) {
|
|
ctx.msg.warning(e instanceof Error ? e.message : ctx.t('chat.shippingNoticeToast.operationFailed'));
|
|
if (chatMsg) chatMsg.shipping_actions_used = false;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (action.id === 'retry_resolve_inventory_source') {
|
|
await ctx.refreshShippingActions();
|
|
ctx.msg.info(ctx.t('chat.shippingNoticeUi.inventorySource.retryResolveDone'));
|
|
return;
|
|
}
|
|
if (action.id === 'edit_inventory_mapping') {
|
|
const taskId = resolveTaskId();
|
|
if (!taskId) {
|
|
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
|
return;
|
|
}
|
|
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
|
return;
|
|
}
|
|
if (action.id === 'upload_inventory_file') {
|
|
ctx.openShippingInventoryPicker(resolveTaskId());
|
|
return;
|
|
}
|
|
if (action.id === 'replace_notice_file') {
|
|
ctx.openShippingNoticePicker(resolveTaskId());
|
|
return;
|
|
}
|
|
if (action.id === 'paste_inventory_json') {
|
|
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
|
return;
|
|
}
|
|
if (action.id === 'reparse_inventory') {
|
|
if (chatMsg?.shipping_actions_used) return;
|
|
const taskId = resolveTaskId();
|
|
if (!taskId) {
|
|
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
|
return;
|
|
}
|
|
if (chatMsg) chatMsg.shipping_actions_used = true;
|
|
const ok = await ctx.executeShippingDecision('reparse_inventory', action.message, { silent: true, taskId });
|
|
if (ok) ctx.openShippingInventoryPicker(taskId);
|
|
return;
|
|
}
|
|
if (action.id && SHIPPING_DECISION_ACTIONS.has(action.id)) {
|
|
if (chatMsg?.shipping_actions_used) return;
|
|
if (chatMsg) chatMsg.shipping_actions_used = true;
|
|
await ctx.executeShippingDecision(action.id, action.message, { taskId: resolveTaskId() });
|
|
return;
|
|
}
|
|
if (chatMsg?.shipping_actions_used) return;
|
|
if (chatMsg) chatMsg.shipping_actions_used = true;
|
|
await ctx.sendShippingMenuMessage(action.message);
|
|
};
|
|
|
|
const handleShippingActionClick = async (
|
|
chatMsg: ChatMessage & { shipping_actions_used?: boolean },
|
|
action: ShippingActionButton,
|
|
) => {
|
|
await handleShippingMenuAction(action, chatMsg);
|
|
};
|
|
|
|
return { handleShippingMenuAction, handleShippingActionClick };
|
|
}
|