refactor(frontend): 重构前端第二版

This commit is contained in:
sophie committed 2026-06-11 13:47:06 +08:00
1 parent 2631f78b00
commit 4b562cfa82
205 files changed
+15399 -12015

No files matched your search

@@ -0,0 +1,360 @@
/**
* features/chat/composables/useChatShipping.ts
* 发货通知(出货)编排层:组合 shipping/* 子模块,对外暴露 ChatView 所需 API。
*
* 子模块职责:
* shippingText / shippingMenu / shippingIntents … 纯函数
* useChatShippingRefresh 动作按钮刷新
* useChatShippingMappingForm 库存列映射表单
* useChatShippingDecision 人工决策与手工上传
* useChatShippingMenuHandler 气泡动作按钮点击
* useChatShippingUploadHandler 文件上传与建议提示
* useChatShippingSendHandler handleSend 前置拦截
*
* 消息类型约定(写入 messages 列表):
* - shipping-inventory-mapping:库存列映射表单
*/
import {
computed,
ref,
watch,
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
extractShippingActionsDirective,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingInventorySampleRowText,
hasShippingInventorySampleRows,
normalizeShippingHeaderForDisplay,
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
loadHistory: () => Promise<void>;
input: Ref<string>;
chatScrollContainer: Ref<HTMLElement | null>;
attachments: Ref<PendingAttachment[]>;
selectedKb: Ref<string>;
isUploadingAttachments: Ref<boolean>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
presetQuestion: ComputedRef<string>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
newLocalMessageId: (prefix: string) => string;
stripReasoningPrelude: (text: string) => string;
sendMessage: (
content: string,
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
}
export function useChatShipping(options: UseChatShippingOptions) {
const {
deps: { t, msg, router, route },
currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
history,
loadHistory,
input,
chatScrollContainer,
attachments,
selectedKb,
isUploadingAttachments,
attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
let invokeHandleSend: (() => Promise<void>) | null = null;
const shippingBindSend = (fn: () => Promise<void>) => {
invokeHandleSend = fn;
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const allowsSendWithAttachmentsOnly = computed(
() => isShippingNoticeAgent.value && attachments.value.length > 0,
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => {
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
return sanitizeShippingConversationText(stripReasoningPrelude(stripped), isShippingNoticeAgent.value);
};
// ── 任务编号状态 ──────────────────────────────────────────
const shippingTaskIdFromQuery = computed(() => {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const resolvedShippingTaskId = ref('');
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant') return String(item.content || '');
}
return '';
};
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent,
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
shippingConversationTaskIdCache,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
messages,
newLocalMessageId,
saveLocalMessageToBackend,
});
const { sendShippingMenuMessage } = createShippingConversationHelpers({
conversationId,
history,
loadHistory,
getActiveShippingTaskId,
currentAgentId,
selectedKb,
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
msg,
t,
});
const {
handleShippingAutoUploadFile,
openShippingInventoryPicker,
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
attachments,
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
t,
});
const { handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
getActiveShippingTaskId,
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
msg,
t,
});
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
isShippingNoticeAgent,
isThinking,
isUploadingAttachments,
messages,
conversationId,
history,
input,
attachments,
shippingAutoFlowRequested,
resolvedShippingTaskId,
currentAgentId,
selectedKb,
attachmentPolicy,
getActiveShippingTaskId,
lastAssistantMessageContent,
sendMessage,
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingAutoUploadFile,
refreshShippingActions,
shippingSuggestedPrompt,
msg,
t,
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
const resumeShippingTaskFromQuery = async () => {
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
input.value = t('chat.shippingNoticeContinue', { taskId });
await invokeHandleSend?.();
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
}
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
};
const onConversationLoadFailed = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
createNewChatView();
void router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
await invokeHandleSend?.();
};
// ── 动作按钮 watch ────────────────────────────────────────
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
const last = msgs.length ? msgs[msgs.length - 1] : null;
return [
String(conversationId.value || ''),
String(msgs.length),
String(last?.role || ''),
String(last?.content || '').slice(-120),
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions();
});
return {
shippingBindSend,
isShippingNoticeAgent,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
hasShippingInventorySampleRows,
getShippingInventorySampleRowText,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
handleShippingActionClick,
handleShippingInventorySelected,
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
onConversationLoadedEmpty,
onConversationLoadFailed,
};
}