refactor(frontend): 重构前端第二版
This commit is contained in:
1 parent
2631f78b00
commit
4b562cfa82
205 files changed
+15399
-12015
No files matched your search
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/api/chat.api.ts
|
||||
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/utils/auth';
|
||||
import { requestJson } from '@/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type {
|
||||
ChatCrossAgentHistoryItem,
|
||||
ChatMessage,
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* features/chat/api/shipping.api.ts
|
||||
* 货代发货 HTTP API:任务列表、上传库存、映射、决策、Excel 生成等。
|
||||
* 后端路由前缀为 /api/workspace/shipping-tasks,由 chat 域 Agent 流程与工作台页面共用。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
ShippingChatActionsResponse,
|
||||
ShippingDecisionResponse,
|
||||
ShippingInventoryUploadResponse,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
async function getJson<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string }).error || res.statusText);
|
||||
}
|
||||
return res.json() as Promise<T>;
|
||||
}
|
||||
|
||||
export const listWorkspaceShippingTasks = (params?: { process_status?: string; limit?: number }) => {
|
||||
const sp = new URLSearchParams();
|
||||
if (params?.process_status) sp.set('process_status', params.process_status);
|
||||
if (params?.limit) sp.set('limit', String(params.limit));
|
||||
const qs = sp.toString();
|
||||
return getJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
|
||||
};
|
||||
|
||||
export const getWorkspaceShippingTask = (taskNo: string) =>
|
||||
getJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
|
||||
|
||||
export const workspaceShippingExportUrl = (taskNo: string) =>
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
|
||||
|
||||
export const getShippingChatActions = (taskNo: string) =>
|
||||
getJson<ShippingChatActionsResponse>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
|
||||
);
|
||||
|
||||
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/upload-inventory`,
|
||||
{ method: 'POST', headers, body: form },
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function applyWorkspaceShippingInventoryMapping(taskNo: string, columnMappingJson: Record<string, unknown>) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/apply-inventory-mapping`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ map_json: columnMappingJson }),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
|
||||
if (!res.ok) {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function createWorkspaceShippingTask(params?: {
|
||||
source_type?: string;
|
||||
conversation_id?: string;
|
||||
raw_content?: string;
|
||||
}) {
|
||||
const res = await fetch('/api/workspace/shipping-tasks', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(params || {}),
|
||||
});
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingTaskCreateResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function createWorkspaceShippingTaskFromNotice(file: File, conversationId?: string) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (conversationId) form.append('conversation_id', conversationId);
|
||||
const headers = getAuthHeaders();
|
||||
delete (headers as Record<string, string>)['Content-Type'];
|
||||
const res = await fetch('/api/workspace/shipping-tasks/create-from-notice', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: form,
|
||||
});
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ decision, ...(comment ? { comment } : {}) }),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function matchWorkspaceShippingInventory(taskNo: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** Hxops 聊天兜底:等同 Dify auto_progress Tool */
|
||||
export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/auto-progress`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(lang ? { lang } : {}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function markWorkspaceShippingManualUploaded(taskNo: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function generateWorkspaceShippingExcel(taskNo: string) {
|
||||
const res = await fetch(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
);
|
||||
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
|
||||
if (!res.ok || body.status === 'failed') {
|
||||
throw new Error(body.error || body.message || res.statusText);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** 货代发货 Agent 显示名称,用于路由与 Agent 匹配 */
|
||||
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
|
||||
|
||||
export type {
|
||||
ShippingChatActionsResponse,
|
||||
ShippingDecisionResponse,
|
||||
ShippingInventoryUploadResponse,
|
||||
ShippingNoticeUploadResponse,
|
||||
ShippingTaskCreateResponse,
|
||||
ShippingTaskDetail,
|
||||
ShippingTaskSummary,
|
||||
} from '../types/shipping.api.types';
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* features/chat/components/ChatBrowserPanel.vue
|
||||
* 内置浏览器侧栏 UI:移动端遮罩、拖拽分隔条与 iframe 预览区。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { ExternalLink, Globe, RotateCw, X } from 'lucide-vue-next';
|
||||
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
const draftUrl = defineModel<string>('draftUrl', { required: true });
|
||||
|
||||
defineProps<{
|
||||
currentUrl: string;
|
||||
frameKey: number;
|
||||
panelStyle: { width: string } | undefined;
|
||||
isResizing: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
load: [];
|
||||
refresh: [];
|
||||
'open-new-tab': [];
|
||||
'url-enter': [event: KeyboardEvent];
|
||||
'start-resize': [event: MouseEvent];
|
||||
close: [];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="open">
|
||||
<div
|
||||
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm lg:hidden"
|
||||
@click="emit('close')"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="relative z-10 hidden w-2 shrink-0 cursor-col-resize bg-transparent lg:block"
|
||||
@mousedown="emit('start-resize', $event)"
|
||||
>
|
||||
<div
|
||||
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
|
||||
:class="isResizing ? 'bg-brand-500' : 'bg-slate-200'"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside
|
||||
class="fixed inset-y-0 right-0 z-50 flex w-full max-w-[100vw] flex-col border-l border-default bg-surface shadow-2xl sm:w-[420px] lg:static lg:z-0 lg:w-[420px] lg:shadow-none"
|
||||
:style="panelStyle"
|
||||
>
|
||||
<div class="flex items-center justify-between border-b border-default px-4 py-3">
|
||||
<div class="flex items-center gap-2 text-sm font-semibold text-secondary">
|
||||
<Globe class="h-4 w-4 text-brand-500" />
|
||||
{{ $t('chat.browser') }}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-muted transition-colors hover-surface-soft hover:text-secondary"
|
||||
:title="$t('chat.closeBrowser')"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 border-b border-default px-3 py-3">
|
||||
<input
|
||||
v-model="draftUrl"
|
||||
type="text"
|
||||
:placeholder="$t('chat.browserInputPlaceholder')"
|
||||
class="flex-1 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-primary outline-none transition focus:border-brand-400 focus:bg-surface"
|
||||
@keydown="emit('url-enter', $event)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-brand-600 px-3 py-2 text-xs font-medium text-white transition-colors hover:bg-brand-500"
|
||||
@click="emit('load')"
|
||||
>
|
||||
{{ $t('chat.open') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
|
||||
:title="$t('chat.refresh')"
|
||||
@click="emit('refresh')"
|
||||
>
|
||||
<RotateCw class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
|
||||
:title="$t('chat.openInNewTab')"
|
||||
@click="emit('open-new-tab')"
|
||||
>
|
||||
<ExternalLink class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 flex-1 bg-slate-100">
|
||||
<div
|
||||
v-if="!currentUrl"
|
||||
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-muted"
|
||||
>
|
||||
<Globe class="h-8 w-8 text-brand-500" />
|
||||
<div>{{ $t('chat.browserHint1') }}</div>
|
||||
<div class="text-xs">{{ $t('chat.browserHint2') }}</div>
|
||||
</div>
|
||||
<iframe
|
||||
v-else
|
||||
:key="frameKey"
|
||||
:src="currentUrl"
|
||||
class="h-full w-full border-0 bg-surface"
|
||||
allow="clipboard-read; clipboard-write"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
</template>
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* features/chat/components/ChatGuideModal.vue
|
||||
* Agent 学习之窗:指南目录与视频 / PDF / 图片预览。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { BookOpen, FileText, Image as ImageIcon, PanelLeftClose, PanelLeftOpen, Play, X } from 'lucide-vue-next';
|
||||
import type { AgentGuide } from '../composables/useChatGuides';
|
||||
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
const activeGuideId = defineModel<number | null>('activeGuideId', { required: true });
|
||||
const showSidebar = defineModel<boolean>('showSidebar', { required: true });
|
||||
|
||||
defineProps<{
|
||||
agentName: string;
|
||||
guides: AgentGuide[];
|
||||
activeGuide: AgentGuide | undefined;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4 backdrop-blur-sm"
|
||||
>
|
||||
<div class="flex h-[85vh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface shadow-xl">
|
||||
<div class="flex shrink-0 items-center justify-between border-b border-default bg-surface px-6 py-4">
|
||||
<h3 class="flex items-center gap-2 text-lg font-bold text-primary">
|
||||
<BookOpen class="h-5 w-5 text-brand-600" />
|
||||
{{ agentName }} - 学习之窗
|
||||
</h3>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1.5 rounded-lg border border-transparent px-3 py-1.5 text-sm font-medium text-brand-600 transition-colors hover:border-brand-100 hover:bg-brand-50 hover:text-brand-700"
|
||||
@click="showSidebar = !showSidebar"
|
||||
>
|
||||
<component :is="showSidebar ? PanelLeftClose : PanelLeftOpen" class="h-4 w-4" />
|
||||
{{ showSidebar ? '收起目录' : '展开目录' }}
|
||||
</button>
|
||||
<div class="h-5 w-px bg-default" />
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg p-1 text-muted transition-colors hover:bg-surface-soft hover:text-primary"
|
||||
@click="open = false"
|
||||
>
|
||||
<X class="h-6 w-6" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div
|
||||
v-show="showSidebar"
|
||||
class="absolute z-10 h-full w-64 shrink-0 space-y-2 overflow-y-auto border-r border-default bg-surface-soft p-4 shadow-xl transition-transform duration-300 md:relative md:shadow-none"
|
||||
:class="showSidebar ? 'translate-x-0' : '-translate-x-full absolute'"
|
||||
>
|
||||
<button
|
||||
v-for="guide in guides"
|
||||
:key="guide.id"
|
||||
type="button"
|
||||
class="w-full rounded-xl border px-4 py-3 text-left transition-all"
|
||||
:class="activeGuideId === guide.id ? 'border-brand-200 bg-brand-50 text-brand-700 shadow-sm' : 'border-transparent bg-surface hover:border-default hover:shadow-sm'"
|
||||
@click="activeGuideId = guide.id"
|
||||
>
|
||||
<div class="mb-1 flex items-center gap-2">
|
||||
<component
|
||||
:is="guide.file_type === 'video' ? Play : (guide.file_type === 'pdf' ? FileText : ImageIcon)"
|
||||
class="h-4 w-4 shrink-0"
|
||||
/>
|
||||
<span class="truncate text-sm font-medium">{{ guide.file_name }}</span>
|
||||
</div>
|
||||
<p
|
||||
v-if="guide.remark"
|
||||
class="truncate text-xs opacity-70"
|
||||
:class="activeGuideId === guide.id ? 'text-brand-600' : 'text-muted'"
|
||||
>
|
||||
{{ guide.remark }}
|
||||
</p>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="relative flex flex-1 items-center justify-center overflow-hidden bg-[#ebedf0] dark:bg-gray-900">
|
||||
<template v-if="activeGuide">
|
||||
<video
|
||||
v-if="activeGuide.file_type === 'video'"
|
||||
:key="'video-' + activeGuide.id"
|
||||
:src="activeGuide.file_url || activeGuide.file_path"
|
||||
controls
|
||||
class="h-full w-full bg-black object-contain"
|
||||
/>
|
||||
<iframe
|
||||
v-else-if="activeGuide.file_type === 'pdf'"
|
||||
:key="'pdf-' + activeGuide.id"
|
||||
:src="activeGuide.file_url || activeGuide.file_path"
|
||||
class="h-full w-full border-none bg-white"
|
||||
/>
|
||||
<img
|
||||
v-else
|
||||
:key="'img-' + activeGuide.id"
|
||||
:src="activeGuide.file_url || activeGuide.file_path"
|
||||
class="max-h-full max-w-full object-contain"
|
||||
/>
|
||||
</template>
|
||||
<div v-else class="flex flex-col items-center gap-3 text-muted">
|
||||
<BookOpen class="h-12 w-12 opacity-20" />
|
||||
<p class="text-sm">请选择左侧指南进行查阅</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* features/chat/components/ChatInputBar.vue
|
||||
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
Check,
|
||||
ChevronDown,
|
||||
Database,
|
||||
Globe,
|
||||
Link2,
|
||||
Loader2,
|
||||
Mic,
|
||||
Paperclip,
|
||||
Send,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
|
||||
export interface ChatInputAttachmentPolicy {
|
||||
anyEnabled: boolean;
|
||||
canLocal: boolean;
|
||||
canRemote: boolean;
|
||||
accept: string;
|
||||
}
|
||||
|
||||
const inputValue = defineModel<string>({ required: true });
|
||||
const selectedKb = defineModel<string>('selectedKb', { required: true });
|
||||
|
||||
const props = defineProps<{
|
||||
attachments: PendingAttachment[];
|
||||
attachmentPolicy: ChatInputAttachmentPolicy;
|
||||
availableKbOptions: string[];
|
||||
kbDropdownDisabled: boolean;
|
||||
isThinking: boolean;
|
||||
isVoiceRecording: boolean;
|
||||
isVoiceTranscribing: boolean;
|
||||
isUploadingAttachments: boolean;
|
||||
canSendMessage: boolean;
|
||||
isShippingNoticeAgent: boolean;
|
||||
shippingSuggestedPrompt: string;
|
||||
/** 用对象包裹 Ref,避免 template 自动解包 */
|
||||
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
|
||||
getKbLabel: (kb: string) => string;
|
||||
browserPanelOpen: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
send: [];
|
||||
'toggle-browser': [];
|
||||
'voice-click': [];
|
||||
'remove-attachment': [id: string];
|
||||
'local-files-selected': [event: Event];
|
||||
'add-remote-url': [url: string];
|
||||
'shipping-inventory-selected': [event: Event];
|
||||
'use-shipping-suggested-prompt': [];
|
||||
}>();
|
||||
|
||||
const filePickerRef = ref<HTMLInputElement | null>(null);
|
||||
const attachmentMenuRef = ref<HTMLElement | null>(null);
|
||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
|
||||
const showAttachmentMenu = ref(false);
|
||||
const showAttachmentUrlPanel = ref(false);
|
||||
const showKbDropdown = ref(false);
|
||||
const attachmentUrlInput = ref('');
|
||||
|
||||
const closeAttachmentMenu = () => {
|
||||
showAttachmentMenu.value = false;
|
||||
showAttachmentUrlPanel.value = false;
|
||||
attachmentUrlInput.value = '';
|
||||
};
|
||||
|
||||
const toggleAttachmentMenu = () => {
|
||||
if (props.isThinking || props.isUploadingAttachments) return;
|
||||
showAttachmentMenu.value = !showAttachmentMenu.value;
|
||||
if (!showAttachmentMenu.value) {
|
||||
showAttachmentUrlPanel.value = false;
|
||||
attachmentUrlInput.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const selectAttachmentLocal = () => {
|
||||
if (!props.attachmentPolicy.canLocal) return;
|
||||
closeAttachmentMenu();
|
||||
filePickerRef.value?.click();
|
||||
};
|
||||
|
||||
const selectAttachmentUrl = async () => {
|
||||
if (!props.attachmentPolicy.canRemote) return;
|
||||
showAttachmentMenu.value = true;
|
||||
showAttachmentUrlPanel.value = true;
|
||||
await nextTick();
|
||||
attachmentUrlInputRef.value?.focus();
|
||||
};
|
||||
|
||||
const toggleKbDropdown = () => {
|
||||
if (props.kbDropdownDisabled) {
|
||||
showKbDropdown.value = false;
|
||||
return;
|
||||
}
|
||||
showKbDropdown.value = !showKbDropdown.value;
|
||||
};
|
||||
|
||||
const selectKb = (option: string) => {
|
||||
if (!props.availableKbOptions.includes(option)) return;
|
||||
selectedKb.value = option;
|
||||
showKbDropdown.value = false;
|
||||
};
|
||||
|
||||
const submitRemoteUrl = () => {
|
||||
const raw = attachmentUrlInput.value.trim();
|
||||
if (!raw) return;
|
||||
emit('add-remote-url', raw);
|
||||
closeAttachmentMenu();
|
||||
};
|
||||
|
||||
const bindShippingPickerRef = (el: unknown) => {
|
||||
props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
|
||||
};
|
||||
|
||||
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||||
const target = event.target as Node | null;
|
||||
if (!target) return;
|
||||
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
|
||||
showKbDropdown.value = false;
|
||||
}
|
||||
if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) {
|
||||
closeAttachmentMenu();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
|
||||
<div class="relative mx-auto max-w-4xl">
|
||||
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
|
||||
<textarea
|
||||
v-model="inputValue"
|
||||
rows="1"
|
||||
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
|
||||
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
|
||||
style="min-height: 44px; max-height: 220px;"
|
||||
:disabled="isThinking || isVoiceTranscribing"
|
||||
spellcheck="false"
|
||||
autocorrect="off"
|
||||
autocapitalize="off"
|
||||
@keydown.enter.prevent="emit('send')"
|
||||
/>
|
||||
|
||||
<input
|
||||
:ref="bindShippingPickerRef"
|
||||
type="file"
|
||||
class="hidden"
|
||||
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
|
||||
@change="emit('shipping-inventory-selected', $event)"
|
||||
/>
|
||||
|
||||
<input
|
||||
ref="filePickerRef"
|
||||
type="file"
|
||||
multiple
|
||||
class="hidden"
|
||||
:accept="attachmentPolicy.accept || undefined"
|
||||
@change="emit('local-files-selected', $event)"
|
||||
/>
|
||||
|
||||
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
|
||||
<div
|
||||
v-for="a in attachments"
|
||||
:key="a.id"
|
||||
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
|
||||
>
|
||||
<span class="max-w-[220px] truncate">
|
||||
{{ a.kind === 'local' ? a.file.name : a.url }}
|
||||
</span>
|
||||
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
|
||||
<X class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && attachments.length > 0"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
|
||||
@click="emit('use-shipping-suggested-prompt')"
|
||||
>
|
||||
{{ shippingSuggestedPrompt || '推荐问题' }}
|
||||
</button>
|
||||
<span>点发送开始处理</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 flex items-center justify-between px-2 pb-1">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isVoiceTranscribing"
|
||||
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
|
||||
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="isVoiceRecording ? 'animate-pulse text-red-500' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
|
||||
@click="emit('voice-click')"
|
||||
>
|
||||
<Loader2 v-if="isVoiceTranscribing" class="h-5 w-5 animate-spin" />
|
||||
<Mic v-else class="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
title="附件"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@click="toggleAttachmentMenu"
|
||||
>
|
||||
<Paperclip class="h-5 w-5" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showAttachmentMenu"
|
||||
class="absolute bottom-full left-0 mb-2 w-72 animate-fade-in overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl"
|
||||
>
|
||||
<button
|
||||
v-if="attachmentPolicy.canLocal"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="selectAttachmentLocal"
|
||||
>
|
||||
<Paperclip class="h-4 w-4 text-brand-500" />
|
||||
上传本地文件
|
||||
</button>
|
||||
<button
|
||||
v-if="attachmentPolicy.canRemote"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="selectAttachmentUrl"
|
||||
>
|
||||
<Link2 class="h-4 w-4 text-brand-500" />
|
||||
粘贴 URL
|
||||
</button>
|
||||
<div v-if="showAttachmentUrlPanel" class="px-3 py-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<input
|
||||
ref="attachmentUrlInputRef"
|
||||
v-model="attachmentUrlInput"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
placeholder="粘贴附件 URL(http/https)"
|
||||
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
|
||||
@keydown.enter.prevent="submitRemoteUrl"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="添加"
|
||||
@click="submitRemoteUrl"
|
||||
>
|
||||
<Check class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking || isUploadingAttachments"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
|
||||
title="取消"
|
||||
@click="closeAttachmentMenu"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="kbMenuRef" class="relative">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="kbDropdownDisabled"
|
||||
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
@click="toggleKbDropdown"
|
||||
>
|
||||
<Database class="h-3.5 w-3.5 text-brand-500" />
|
||||
{{ getKbLabel(selectedKb) }} <ChevronDown class="h-3 w-3" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showKbDropdown && !kbDropdownDisabled"
|
||||
class="absolute bottom-full left-0 mb-2 w-36 animate-fade-in overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl"
|
||||
>
|
||||
<button
|
||||
v-for="option in availableKbOptions"
|
||||
:key="option"
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
|
||||
:class="{ 'font-bold text-brand-700': selectedKb === option }"
|
||||
@click="selectKb(option)"
|
||||
>
|
||||
{{ getKbLabel(option) }}
|
||||
<Check v-if="selectedKb === option" class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
:disabled="isThinking"
|
||||
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
|
||||
@click="emit('toggle-browser')"
|
||||
>
|
||||
<Globe class="h-3.5 w-3.5 text-brand-500" />
|
||||
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
:disabled="!canSendMessage"
|
||||
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:class="!canSendMessage
|
||||
? 'border-default bg-slate-100 text-muted'
|
||||
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
|
||||
@click="emit('send')"
|
||||
>
|
||||
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
|
||||
<Send v-else class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 text-center text-[11px] text-muted">
|
||||
{{ $t('chat.disclaimer') }}
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/chat/components/ChatLeaveAgentDialog.vue
|
||||
* 请假 OA:选择代理人 / 申请人弹窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { Loader2, Search, X } from 'lucide-vue-next';
|
||||
import type { LeaveAgentOption } from '../types/leave.types';
|
||||
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
const keyword = defineModel<string>('keyword', { required: true });
|
||||
|
||||
defineProps<{
|
||||
selectRole: 'agent' | 'applicant';
|
||||
options: LeaveAgentOption[];
|
||||
loading: boolean;
|
||||
page: number;
|
||||
hasMore: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
search: [];
|
||||
'load-more': [];
|
||||
'load-all': [];
|
||||
select: [option: LeaveAgentOption];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="dialog-overlay z-[100] items-center"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<div class="dialog-panel flex max-h-[80vh] max-w-2xl flex-col">
|
||||
<div class="dialog-header">
|
||||
<div>
|
||||
<h3 class="section-title">
|
||||
{{ $t('chat.selectWho', { role: selectRole === 'agent' ? $t('chat.leaveAgent') : $t('chat.leaveApplicant') }) }}
|
||||
</h3>
|
||||
<p class="section-desc mt-1">{{ $t('chat.oaDataConnected') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="emit('close')">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="dialog-body space-y-4 border-t-0 pt-4">
|
||||
<div class="relative shrink-0">
|
||||
<input
|
||||
v-model="keyword"
|
||||
type="text"
|
||||
:placeholder="$t('chat.searchByNameOrEmployeeId')"
|
||||
class="input-field pr-10"
|
||||
@keydown.enter="emit('search')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-muted hover:text-brand-600"
|
||||
@click="emit('search')"
|
||||
>
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="max-h-[50vh] flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
|
||||
<div v-if="loading && page === 1" class="flex justify-center py-8">
|
||||
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||
</div>
|
||||
<div v-else-if="options.length === 0" class="py-8 text-center text-sm text-muted">
|
||||
{{ $t('chat.noData') }}
|
||||
</div>
|
||||
<template v-else>
|
||||
<button
|
||||
v-for="option in options"
|
||||
:key="option.uid"
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between rounded-2xl border border-default px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50"
|
||||
@click="emit('select', option)"
|
||||
>
|
||||
<div class="space-y-1">
|
||||
<div class="text-sm font-semibold text-primary">{{ option.name }}</div>
|
||||
<div class="text-xs text-muted">UID:{{ option.uid }}</div>
|
||||
</div>
|
||||
<div class="text-right text-xs text-muted">
|
||||
<div>{{ $t('chat.employeeId') }}:{{ option.employeeId }}</div>
|
||||
<div>{{ $t('chat.name') }}:{{ option.name }}</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div v-if="hasMore" class="flex items-center justify-center space-x-6 py-4">
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-muted hover:text-secondary disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="emit('load-all')"
|
||||
>
|
||||
{{ $t('chat.loadAll') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
|
||||
:disabled="loading"
|
||||
@click="emit('load-more')"
|
||||
>
|
||||
{{ loading ? $t('chat.loading') : $t('chat.loadMore') }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="py-4 text-center text-xs text-muted">{{ $t('chat.noMoreData') }}</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* features/chat/components/ChatMessageList.vue
|
||||
* 消息列表主区域:滚动容器、欢迎页、消息气泡与思考中占位。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { Ref } from 'vue';
|
||||
import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue';
|
||||
import ChatThinkingBubble from './ChatThinkingBubble.vue';
|
||||
import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue';
|
||||
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
|
||||
import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const {
|
||||
messages,
|
||||
shouldRenderMessage,
|
||||
scrollContainerHolder,
|
||||
} = defineProps<{
|
||||
messages: ChatMessage[];
|
||||
agentName: string;
|
||||
suggestedQuestionsStyle: 'plain' | 'styled';
|
||||
styledSections: WelcomeQuestionSection[];
|
||||
suggestedQuestions: WelcomeQuestionItem[];
|
||||
showThinkingBubble: boolean;
|
||||
isThinking: boolean;
|
||||
showChatRating: boolean;
|
||||
copiedIndex: number | null;
|
||||
isShippingNoticeAgent: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
shouldRenderMessage: (msg: ChatMessage) => boolean;
|
||||
/** 供父级滚动逻辑绑定 main 元素 */
|
||||
scrollContainerHolder: { el: Ref<HTMLElement | null> };
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
copy: [payload: { message: ChatMessage; index: number }];
|
||||
edit: [content: string];
|
||||
resend: [content: string];
|
||||
regenerate: [];
|
||||
'open-feedback': [index: number];
|
||||
'select-question': [question: string];
|
||||
}>();
|
||||
|
||||
const bindScrollContainer = (node: unknown) => {
|
||||
scrollContainerHolder.el.value = (node as HTMLElement | null) ?? null;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main
|
||||
:ref="bindScrollContainer"
|
||||
class="flex-1 p-3 md:p-8"
|
||||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
|
||||
>
|
||||
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
|
||||
<ChatWelcomePanel
|
||||
v-if="messages.length === 0"
|
||||
:agent-name="agentName"
|
||||
:suggested-questions-style="suggestedQuestionsStyle"
|
||||
:styled-sections="styledSections"
|
||||
:suggested-questions="suggestedQuestions"
|
||||
@select-question="emit('select-question', $event)"
|
||||
/>
|
||||
|
||||
<template v-for="(msg, index) in messages" :key="index">
|
||||
<ChatMessageBubble
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
:message="msg"
|
||||
:index="index"
|
||||
:message-count="messages.length"
|
||||
:is-thinking="isThinking"
|
||||
:show-chat-rating="showChatRating"
|
||||
:copied-index="copiedIndex"
|
||||
:is-shipping-notice-agent="isShippingNoticeAgent"
|
||||
:handlers="handlers"
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
@copy="emit('copy', { message: msg, index })"
|
||||
@edit="emit('edit', $event)"
|
||||
@resend="emit('resend', $event)"
|
||||
@regenerate="emit('regenerate')"
|
||||
@open-feedback="emit('open-feedback', index)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<ChatThinkingBubble v-if="showThinkingBubble" />
|
||||
<div v-if="messages.length > 0" class="h-2 md:h-3" />
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* features/chat/components/ChatMobileHeader.vue
|
||||
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import { BookOpen, History, LayoutGrid } from 'lucide-vue-next';
|
||||
|
||||
export interface ChatMobileHeaderAgent {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
agentName: string;
|
||||
hasAgentGuides: boolean;
|
||||
userAgents: ChatMobileHeaderAgent[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'open-guide': [];
|
||||
'go-history': [];
|
||||
'open-agent-popover': [];
|
||||
'switch-agent': [agent: ChatMobileHeaderAgent];
|
||||
}>();
|
||||
|
||||
const showAgentPopover = ref(false);
|
||||
const popoverRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const toggleAgentPopover = () => {
|
||||
showAgentPopover.value = !showAgentPopover.value;
|
||||
if (showAgentPopover.value) {
|
||||
emit('open-agent-popover');
|
||||
}
|
||||
};
|
||||
|
||||
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
|
||||
const target = event.target as Node | null;
|
||||
if (!target) return;
|
||||
if (showAgentPopover.value && popoverRef.value && !popoverRef.value.contains(target)) {
|
||||
showAgentPopover.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const onSwitchAgent = (agent: ChatMobileHeaderAgent) => {
|
||||
showAgentPopover.value = false;
|
||||
emit('switch-agent', agent);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
document.addEventListener('touchstart', handleClickOutside, { passive: true });
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('mousedown', handleClickOutside);
|
||||
document.removeEventListener('touchstart', handleClickOutside);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="relative flex items-center justify-between border-b border-default bg-surface px-4 py-2.5">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">
|
||||
AI
|
||||
</div>
|
||||
<span class="text-sm font-semibold text-primary">{{ agentName }}</span>
|
||||
<button
|
||||
v-if="hasAgentGuides"
|
||||
type="button"
|
||||
class="ml-1 flex items-center gap-1.5 rounded-lg border border-brand-300 bg-brand-100 px-3 py-1.5 text-xs font-bold text-brand-700 shadow-sm transition-all hover:border-brand-400 hover:bg-brand-200"
|
||||
@click="emit('open-guide')"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
学习之窗
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
|
||||
:title="$t('chat.agents')"
|
||||
@click="toggleAgentPopover"
|
||||
>
|
||||
<LayoutGrid class="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
|
||||
:title="$t('chat.history')"
|
||||
@click="emit('go-history')"
|
||||
>
|
||||
<History class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
v-if="showAgentPopover"
|
||||
ref="popoverRef"
|
||||
class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-default bg-surface p-3 shadow-xl"
|
||||
>
|
||||
<div class="mb-2 text-xs font-medium text-muted">{{ $t('chat.agents') }}</div>
|
||||
<div class="grid grid-cols-2 gap-2">
|
||||
<button
|
||||
v-for="agent in userAgents"
|
||||
:key="agent.id"
|
||||
type="button"
|
||||
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover-surface-soft"
|
||||
@click="onSwitchAgent(agent)"
|
||||
>
|
||||
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600">
|
||||
{{ agent.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="w-full truncate text-xs font-medium text-secondary">{{ agent.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* features/chat/components/ChatOALoginDialog.vue
|
||||
* 请假 OA 系统登录弹窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
const employeeId = defineModel<string>('employeeId', { required: true });
|
||||
const password = defineModel<string>('password', { required: true });
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [];
|
||||
cancel: [];
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="open"
|
||||
class="dialog-overlay z-[9999] items-center"
|
||||
@click.self="emit('cancel')"
|
||||
>
|
||||
<div class="dialog-panel max-w-sm">
|
||||
<div class="dialog-header dialog-header--compact justify-center border-0 pb-2">
|
||||
<h3 class="section-title text-center">{{ $t('chat.loginOaSystem') }}</h3>
|
||||
</div>
|
||||
<div class="dialog-body space-y-4 border-t-0 pt-0">
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ $t('chat.employeeId') }}</span>
|
||||
<input
|
||||
v-model="employeeId"
|
||||
type="text"
|
||||
disabled
|
||||
class="input-field bg-surface-soft"
|
||||
/>
|
||||
</label>
|
||||
<label class="block space-y-1.5">
|
||||
<span class="label-field">{{ $t('login.password') }}</span>
|
||||
<input
|
||||
v-model="password"
|
||||
type="password"
|
||||
:placeholder="$t('chat.enterOaPassword')"
|
||||
class="input-field"
|
||||
@keyup.enter="emit('confirm')"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div class="dialog-footer">
|
||||
<button type="button" class="btn-secondary" @click="emit('cancel')">
|
||||
{{ $t('profile.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary btn-sm" @click="emit('confirm')">
|
||||
{{ $t('chat.confirmLogin') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* features/chat/components/ChatQueryPreviewDialog.vue
|
||||
* Text2SQL 查询结果全量预览弹窗 UI。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Loader2, X } from 'lucide-vue-next';
|
||||
import type { QueryPreviewState } from '../composables/useChatQueryPreview';
|
||||
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
|
||||
const props = defineProps<{
|
||||
loading: boolean;
|
||||
error: string;
|
||||
state: QueryPreviewState;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'change-page': [delta: number];
|
||||
}>();
|
||||
|
||||
const totalPages = computed(() =>
|
||||
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="dialog-overlay z-[120] items-center"
|
||||
@click.self="emit('close')"
|
||||
>
|
||||
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1280px)] max-w-[1280px] flex-col">
|
||||
<div class="dialog-header">
|
||||
<div>
|
||||
<h3 class="section-title">查询结果全量预览</h3>
|
||||
<p class="section-desc mt-1">{{ state.query || state.title }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3 text-sm text-secondary">
|
||||
<div>共 {{ state.total || 0 }} 条,当前第 {{ state.page }} / {{ totalPages }} 页</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="loading || state.page <= 1"
|
||||
@click="emit('change-page', -1)"
|
||||
>
|
||||
上一页
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="loading || state.page >= totalPages"
|
||||
@click="emit('change-page', 1)"
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||
<div v-if="loading" class="flex h-56 items-center justify-center">
|
||||
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||
</div>
|
||||
<div v-else-if="!state.columns.length" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||
暂无可预览数据
|
||||
</div>
|
||||
<table v-else class="min-w-full border-collapse text-sm">
|
||||
<thead class="sticky top-0 z-10 bg-slate-50">
|
||||
<tr>
|
||||
<th
|
||||
v-for="column in state.columns"
|
||||
:key="`query-preview-col-${column}`"
|
||||
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
|
||||
>
|
||||
{{ column }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(row, rowIndex) in state.rows"
|
||||
:key="`query-preview-row-${rowIndex}`"
|
||||
class="odd:bg-white even:bg-slate-50/50"
|
||||
>
|
||||
<td
|
||||
v-for="(cell, cellIndex) in row"
|
||||
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
|
||||
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
|
||||
>
|
||||
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,332 @@
|
||||
/**
|
||||
* features/chat/components/ChatSidebar.vue
|
||||
* 桌面端聊天侧栏:Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
import {
|
||||
BookOpen,
|
||||
Briefcase,
|
||||
LayoutGrid,
|
||||
LogOut,
|
||||
MessageSquareText,
|
||||
Moon,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
Plus,
|
||||
Settings,
|
||||
Sparkles,
|
||||
Sun,
|
||||
X,
|
||||
} from 'lucide-vue-next';
|
||||
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
|
||||
import type { DisplayHistoryItem } from '../types/chat.types';
|
||||
|
||||
export interface ChatSidebarAgent {
|
||||
id: number;
|
||||
name: string;
|
||||
icon_url?: string;
|
||||
}
|
||||
|
||||
const collapsed = defineModel<boolean>('collapsed', { required: true });
|
||||
const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true });
|
||||
|
||||
const { currentUser } = defineProps<{
|
||||
isOpen: boolean;
|
||||
currentAgent: { name?: string } | null;
|
||||
agentDescription: string;
|
||||
hasAgentGuides: boolean;
|
||||
displayHistory: DisplayHistoryItem[];
|
||||
activeHistoryKey: string;
|
||||
userAgents: ChatSidebarAgent[];
|
||||
currentUser: Record<string, unknown> | null;
|
||||
appliedTheme: string;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'new-chat': [];
|
||||
'open-guide': [];
|
||||
'history-select': [item: DisplayHistoryItem];
|
||||
'clear-all-history': [];
|
||||
'delete-history-item': [id: string, event: Event];
|
||||
'switch-agent': [agent: ChatSidebarAgent];
|
||||
'toggle-theme': [];
|
||||
'open-feedback': [];
|
||||
'go-workspace': [];
|
||||
'go-admin': [];
|
||||
logout: [];
|
||||
}>();
|
||||
|
||||
const showUserDropdown = ref(false);
|
||||
const userMenuRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
|
||||
const target = event.target as Node | null;
|
||||
if (!target) return;
|
||||
if (showUserDropdown.value && userMenuRef.value && !userMenuRef.value.contains(target)) {
|
||||
showUserDropdown.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||
});
|
||||
|
||||
const onNewChat = () => {
|
||||
emit('new-chat');
|
||||
};
|
||||
|
||||
const onLogout = () => {
|
||||
showUserDropdown.value = false;
|
||||
emit('logout');
|
||||
};
|
||||
|
||||
const onGoAdmin = () => {
|
||||
showUserDropdown.value = false;
|
||||
emit('go-admin');
|
||||
};
|
||||
|
||||
const userInitial = (fallback: string) => {
|
||||
const name = String(currentUser?.username ?? '').trim();
|
||||
return (name || fallback).charAt(0).toUpperCase();
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside
|
||||
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r border-default bg-surface transition-all duration-300 ease-in-out md:relative md:translate-x-0"
|
||||
:class="[
|
||||
isOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
|
||||
collapsed ? 'md:w-[72px]' : 'md:w-80',
|
||||
]"
|
||||
>
|
||||
<template v-if="collapsed">
|
||||
<div class="flex h-full w-full flex-col items-center py-4">
|
||||
<button type="button" class="mb-6 text-muted transition-colors hover:text-secondary" @click="collapsed = false">
|
||||
<PanelLeftOpen class="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
<div class="mb-4 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/25">
|
||||
<Sparkles class="h-5 w-5" />
|
||||
</div>
|
||||
|
||||
<button type="button" class="chat-sidebar-btn-icon" :title="$t('chat.createNewChat')" @click="onNewChat">
|
||||
<Plus class="h-5 w-5" />
|
||||
</button>
|
||||
|
||||
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-muted">
|
||||
<button type="button" class="transition-colors hover:text-secondary"><Sparkles class="h-5 w-5" /></button>
|
||||
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
|
||||
{{ userInitial('I') }}
|
||||
</div>
|
||||
<LocaleToggleButton variant="sidebar" icon-size="md" />
|
||||
<button type="button" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
|
||||
<MessageSquareText class="h-5 w-5" />
|
||||
</button>
|
||||
<button type="button" class="transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
|
||||
<Briefcase class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex items-center justify-between p-4">
|
||||
<div class="flex w-full min-w-0 items-center gap-3">
|
||||
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
|
||||
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
|
||||
</div>
|
||||
<div class="group relative flex min-w-0 flex-1 flex-col justify-center">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="truncate font-bold text-primary">{{ currentAgent?.name || 'AI' }}</span>
|
||||
<button
|
||||
v-if="hasAgentGuides"
|
||||
type="button"
|
||||
class="flex items-center gap-1.5 rounded-lg border border-brand-300 bg-brand-100 px-3 py-1.5 text-xs font-bold text-brand-700 shadow-sm transition-all hover:border-brand-400 hover:bg-brand-200"
|
||||
@click="emit('open-guide')"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
学习之窗
|
||||
</button>
|
||||
</div>
|
||||
<span v-if="agentDescription" class="mt-1 block cursor-help truncate text-[11px] text-muted">
|
||||
{{ agentDescription }}
|
||||
</span>
|
||||
|
||||
<div
|
||||
v-if="agentDescription"
|
||||
class="pointer-events-none invisible absolute left-0 top-[calc(100%+0.25rem)] z-[100] w-[20rem] rounded-xl border border-default bg-surface p-3 opacity-0 shadow-xl transition-all duration-200 group-hover:visible group-hover:opacity-100"
|
||||
>
|
||||
<div class="text-[11px] leading-relaxed text-secondary">
|
||||
{{ agentDescription }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="ml-2 shrink-0 text-muted transition-colors hover:text-secondary" @click="collapsed = true">
|
||||
<PanelLeftClose class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="px-4 pb-4">
|
||||
<button type="button" class="chat-sidebar-btn" @click="onNewChat">
|
||||
<Plus class="h-4 w-4" /> {{ $t('chat.createNewChat') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between px-4 py-2">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
|
||||
<button
|
||||
v-if="displayHistory.length > 0"
|
||||
type="button"
|
||||
class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"
|
||||
@click="emit('clear-all-history')"
|
||||
>
|
||||
{{ $t('chat.clearAll') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="scrollbar-thin flex-1 overflow-y-auto px-2">
|
||||
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">
|
||||
{{ $t('chat.noHistory') }}
|
||||
</div>
|
||||
<div v-else class="space-y-0.5">
|
||||
<div
|
||||
v-for="item in displayHistory"
|
||||
:key="item.conversation_id"
|
||||
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
|
||||
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 truncate px-3 py-2.5 pr-8 text-left text-sm"
|
||||
:class="activeHistoryKey === item.conversation_id
|
||||
? 'font-medium text-brand-700 dark:text-brand-300'
|
||||
: 'text-slate-600 dark:text-slate-300'"
|
||||
@click="emit('history-select', item)"
|
||||
>
|
||||
{{ item.title || $t('chat.newChat') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!item.__runId"
|
||||
type="button"
|
||||
class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100"
|
||||
:title="$t('chat.clearOneRecord')"
|
||||
@click="emit('delete-history-item', item.conversation_id, $event)"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto flex flex-col p-4">
|
||||
<div v-if="userAgents.length > 0 && agentPanelOpen" class="chat-agent-panel">
|
||||
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-muted">
|
||||
<LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-x-2 gap-y-1.5">
|
||||
<button
|
||||
v-for="agent in userAgents"
|
||||
:key="agent.id"
|
||||
type="button"
|
||||
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm"
|
||||
@click="emit('switch-agent', agent)"
|
||||
>
|
||||
<div
|
||||
v-if="agent.icon_url"
|
||||
class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat"
|
||||
:style="{ backgroundImage: `url(${agent.icon_url})` }"
|
||||
/>
|
||||
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600">
|
||||
{{ agent.name.charAt(0) }}
|
||||
</div>
|
||||
<span class="min-w-0 truncate">{{ agent.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="userMenuRef" class="relative flex items-center justify-between text-muted">
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-10 min-w-[2.5rem] items-center justify-center rounded-full bg-brand-600 px-3 text-sm font-bold text-white shadow-sm shadow-brand-500/20 transition-colors hover:bg-brand-700"
|
||||
@click="showUserDropdown = !showUserDropdown"
|
||||
>
|
||||
退出
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-if="showUserDropdown"
|
||||
class="absolute bottom-full left-0 z-50 mb-2 w-56 animate-fade-in rounded-xl border border-subtle bg-surface py-1 shadow-xl"
|
||||
>
|
||||
<div class="flex items-center gap-3 border-b border-subtle px-4 py-3">
|
||||
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-brand-600 text-lg font-bold text-white shadow-sm shadow-brand-500/20">
|
||||
{{ userInitial('U') }}
|
||||
</div>
|
||||
<div class="overflow-hidden">
|
||||
<div class="truncate text-sm font-bold text-primary">{{ currentUser?.username || 'User' }}</div>
|
||||
<div v-if="(currentUser as any)?.employee_id" class="truncate text-xs text-muted">
|
||||
{{ $t('chat.employeeId') }}: {{ (currentUser as any).employee_id }}
|
||||
</div>
|
||||
<div v-else class="truncate text-xs text-muted">{{ currentUser?.role }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="currentUser?.role === 'admin'"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-secondary transition-colors hover:bg-surface-soft"
|
||||
@click="onGoAdmin"
|
||||
>
|
||||
<Settings class="h-4 w-4" />
|
||||
{{ $t('workspace.nav.admin') }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 border-t border-subtle px-4 py-2 text-left text-sm text-red-600 transition-colors hover:bg-red-50"
|
||||
@click="onLogout"
|
||||
>
|
||||
<LogOut class="h-4 w-4" />
|
||||
{{ $t('chat.logout') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3">
|
||||
<button
|
||||
type="button"
|
||||
:class="agentPanelOpen && userAgents.length > 0 ? 'text-brand-600' : ''"
|
||||
class="transition-colors hover:text-secondary"
|
||||
:title="userAgents.length === 0 ? $t('chat.noAvailableAgents') : (agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents'))"
|
||||
@click="userAgents.length === 0 ? undefined : (agentPanelOpen = !agentPanelOpen)"
|
||||
>
|
||||
<LayoutGrid class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="transition-colors hover:text-secondary"
|
||||
:title="appliedTheme === 'dark' ? ($t('theme.switchToLight') || 'Switch to light mode') : ($t('theme.switchToDark') || 'Switch to dark mode')"
|
||||
@click="emit('toggle-theme')"
|
||||
>
|
||||
<Sun v-if="appliedTheme === 'dark'" class="h-4 w-4" />
|
||||
<Moon v-else class="h-4 w-4" />
|
||||
</button>
|
||||
<LocaleToggleButton variant="sidebar" />
|
||||
<button type="button" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
|
||||
<MessageSquareText class="h-4 w-4" />
|
||||
</button>
|
||||
<button type="button" class="transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
|
||||
<Briefcase class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* features/chat/components/ChatThinkingBubble.vue
|
||||
* Agent 思考中占位气泡。
|
||||
*/
|
||||
<template>
|
||||
<div class="mx-auto flex w-full max-w-4xl justify-start">
|
||||
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-default bg-surface/95 px-5 py-3 shadow-md">
|
||||
<div class="flex gap-1">
|
||||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400" />
|
||||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-75" />
|
||||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-150" />
|
||||
</div>
|
||||
<span class="text-sm font-medium text-muted">{{ $t('chat.thinking') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* features/chat/components/ChatViewContent.vue
|
||||
* 对话页主区域:侧栏、消息列表、输入栏与内置浏览器。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
|
||||
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
|
||||
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
|
||||
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
|
||||
const page = useChatPageContext();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChatShell>
|
||||
<template #overlay>
|
||||
<div
|
||||
v-if="page.isSidebarOpen && !page.isMobile"
|
||||
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
|
||||
@click="page.isSidebarOpen = false"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #sidebar>
|
||||
<ChatSidebar
|
||||
v-if="!page.isMobile"
|
||||
v-model:collapsed="page.sidebarCollapsed"
|
||||
v-model:agent-panel-open="page.showAgentPanel"
|
||||
:is-open="page.isSidebarOpen"
|
||||
:current-agent="page.currentAgent"
|
||||
:agent-description="page.agentDescription"
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
:display-history="page.displayHistory"
|
||||
:active-history-key="page.activeHistoryKey"
|
||||
:user-agents="page.userAgents"
|
||||
:current-user="page.currentUser"
|
||||
:applied-theme="page.appliedTheme"
|
||||
@new-chat="page.handleSidebarNewChat"
|
||||
@open-guide="page.openGuideModal"
|
||||
@history-select="page.handleHistorySelect"
|
||||
@clear-all-history="page.clearAllHistory"
|
||||
@delete-history-item="page.deleteHistoryItem"
|
||||
@switch-agent="page.switchToAgent"
|
||||
@toggle-theme="page.toggleLightDark"
|
||||
@open-feedback="page.showGeneralFeedbackDialog = true"
|
||||
@go-workspace="page.goToWorkspace()"
|
||||
@go-admin="page.goToAdmin"
|
||||
@logout="page.handleLogout"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<ChatMobileHeader
|
||||
v-if="page.isMobile && page.currentAgent"
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
:has-agent-guides="page.agentGuides.length > 0"
|
||||
:user-agents="page.userAgents"
|
||||
@open-guide="page.openGuideModal"
|
||||
@go-history="page.goToWorkspace('history')"
|
||||
@open-agent-popover="page.loadUserAgents"
|
||||
@switch-agent="page.switchToAgent"
|
||||
/>
|
||||
|
||||
<div v-if="!page.currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
|
||||
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
|
||||
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="page.currentAgent.type === 'iframe'" class="relative h-full w-full flex-1">
|
||||
<iframe
|
||||
:src="page.currentAgent.extra_config?.iframe_url"
|
||||
class="h-full w-full border-0 bg-surface"
|
||||
allow="microphone; camera; clipboard-read; clipboard-write"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<div class="flex min-h-0 flex-1 flex-col">
|
||||
<ChatMessageList
|
||||
:messages="page.messages"
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
:suggested-questions-style="page.suggestedQuestionsStyle"
|
||||
:styled-sections="page.styledSuggestedQuestionSections"
|
||||
:suggested-questions="page.agentSuggestedQuestions"
|
||||
:show-thinking-bubble="page.shouldShowThinkingBubble"
|
||||
:is-thinking="page.isThinking"
|
||||
:show-chat-rating="page.showChatRating"
|
||||
:copied-index="page.copiedIndex"
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:handlers="page.messageBubbleHandlers"
|
||||
:leave-handlers="page.leaveMessageHandlers"
|
||||
:shipping-handlers="page.shippingMappingHandlers"
|
||||
:should-render-message="page.shouldRenderMessage"
|
||||
:scroll-container-holder="page.scrollContainerHolder"
|
||||
@copy="page.copyToClipboard($event.message, $event.index)"
|
||||
@edit="page.input = $event"
|
||||
@resend="page.handleSend($event)"
|
||||
@regenerate="page.regenerate"
|
||||
@open-feedback="page.handleOpenFeedback($event)"
|
||||
@select-question="page.handleSend"
|
||||
/>
|
||||
|
||||
<ChatInputBar
|
||||
v-model="page.input"
|
||||
v-model:selected-kb="page.selectedKb"
|
||||
:attachments="page.attachments"
|
||||
:attachment-policy="page.attachmentPolicy"
|
||||
:available-kb-options="page.availableKbOptions"
|
||||
:kb-dropdown-disabled="page.kbDropdownDisabled"
|
||||
:is-thinking="page.isThinking"
|
||||
:is-voice-recording="page.isVoiceRecording"
|
||||
:is-voice-transcribing="page.isVoiceTranscribing"
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
:can-send-message="page.canSendMessage"
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
|
||||
:get-kb-label="page.getKbLabel"
|
||||
:browser-panel-open="page.browserPanelOpen"
|
||||
@toggle-browser="page.toggleBrowserPanel"
|
||||
@send="page.handleSend()"
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
@remove-attachment="page.removeAttachment"
|
||||
@local-files-selected="page.handleLocalFilesSelected"
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ChatBrowserPanel
|
||||
v-model:open="page.browserPanelOpen"
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
:current-url="page.browserCurrentUrl"
|
||||
:frame-key="page.browserFrameKey"
|
||||
:panel-style="page.browserPanelStyle"
|
||||
:is-resizing="page.isBrowserResizing"
|
||||
@load="page.browser.loadPage"
|
||||
@refresh="page.browser.refreshPage"
|
||||
@open-new-tab="page.browser.openInNewTab"
|
||||
@url-enter="page.browser.onUrlEnter"
|
||||
@start-resize="page.browser.startResize"
|
||||
@close="page.browser.close"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</ChatShell>
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/chat/components/ChatViewOverlays.vue
|
||||
* 对话页全局弹窗:文件预览、反馈、查询预览、请假 OA、删除确认、学习之窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
|
||||
import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewDialog.vue';
|
||||
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
|
||||
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
|
||||
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
const page = useChatPageContext();
|
||||
|
||||
function onFeedbackSubmitted() {
|
||||
const idx = page.activeFeedbackMessageIndex;
|
||||
const target = idx !== null ? page.messages[idx] : undefined;
|
||||
if (target) target.rated = true;
|
||||
page.msg.success(page.t('chat.feedbackSubmitSuccess'));
|
||||
page.showGeneralFeedbackDialog = false;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FilePreviewModal
|
||||
v-model="page.filePreviewVisible"
|
||||
:file="page.previewFile"
|
||||
:agent-id="page.currentAgentId"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
/>
|
||||
<GeneralFeedbackDialog
|
||||
v-model="page.showGeneralFeedbackDialog"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
source-page="chat"
|
||||
:chat-log-id="page.currentGeneralFeedbackChatLogId"
|
||||
@submitted="onFeedbackSubmitted"
|
||||
/>
|
||||
<ChatQueryPreviewDialog
|
||||
v-model:open="page.showQueryPreviewDialog"
|
||||
:loading="page.queryPreviewLoading"
|
||||
:error="page.queryPreviewError"
|
||||
:state="page.queryPreviewState"
|
||||
@close="page.queryPreview.close"
|
||||
@change-page="page.queryPreview.changePage"
|
||||
/>
|
||||
<ChatLeaveAgentDialog
|
||||
v-model:open="page.showLeaveAgentDialog"
|
||||
v-model:keyword="page.leaveAgentKeyword"
|
||||
:select-role="page.leaveUserSelectRole"
|
||||
:options="page.leaveAgentOptions"
|
||||
:loading="page.leaveAgentLoading"
|
||||
:page="page.leaveAgentPage"
|
||||
:has-more="page.leaveAgentHasMore"
|
||||
@close="page.closeLeaveAgentDialog"
|
||||
@search="page.handleAgentSearch"
|
||||
@load-more="page.loadMoreAgents"
|
||||
@load-all="page.loadAllAgents"
|
||||
@select="page.selectLeaveAgent"
|
||||
/>
|
||||
<ChatOALoginDialog
|
||||
v-model:open="page.showOALoginDialog"
|
||||
v-model:employee-id="page.oaLoginEmployeeId"
|
||||
v-model:password="page.oaLoginPassword"
|
||||
@confirm="page.confirmOALogin"
|
||||
@cancel="page.cancelOALogin"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="page.showDeleteConfirmDialog"
|
||||
:message="page.deleteConfirmMessage"
|
||||
@confirm="page.handleDeleteConfirm"
|
||||
@cancel="page.closeDeleteConfirmDialog"
|
||||
/>
|
||||
<ChatGuideModal
|
||||
v-model:open="page.showGuideModal"
|
||||
v-model:active-guide-id="page.activeGuideId"
|
||||
v-model:show-sidebar="page.showGuideSidebar"
|
||||
:agent-name="page.currentAgent?.name || 'AI'"
|
||||
:guides="page.agentGuides"
|
||||
:active-guide="page.activeGuide"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* features/chat/components/ChatWelcomePanel.vue
|
||||
* 无消息时的欢迎区:Agent 头像、标题与预设问题快捷入口。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Building, CalendarDays } from 'lucide-vue-next';
|
||||
|
||||
export interface WelcomeQuestionItem {
|
||||
question: string;
|
||||
group: string;
|
||||
}
|
||||
|
||||
export interface WelcomeQuestionSection {
|
||||
title: string;
|
||||
questions: WelcomeQuestionItem[];
|
||||
iconType: 'calendar' | 'building';
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
agentName: string;
|
||||
suggestedQuestionsStyle: 'plain' | 'styled';
|
||||
styledSections: WelcomeQuestionSection[];
|
||||
suggestedQuestions: WelcomeQuestionItem[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'select-question': [question: string];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const avatarLabel = computed(() => (props.agentName === '人事规章' ? 'HR' : 'AI'));
|
||||
|
||||
const welcomeTitle = computed(() => (
|
||||
props.agentName === '人事规章'
|
||||
? '你好,我是人事规章 AI 助手'
|
||||
: t('chat.welcomeTitle')
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 w-full flex-col items-center px-4 pb-2 pt-2 md:pb-3">
|
||||
<template v-if="suggestedQuestionsStyle === 'styled' && styledSections.length > 0">
|
||||
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
|
||||
{{ avatarLabel }}
|
||||
</div>
|
||||
<h2 class="mb-6 shrink-0 text-center text-xl font-bold text-primary md:text-2xl">
|
||||
{{ welcomeTitle }}
|
||||
</h2>
|
||||
|
||||
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
|
||||
<div class="mx-auto grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-2">
|
||||
<div
|
||||
v-for="(section, sectionIndex) in styledSections"
|
||||
:key="`${section.title}-${sectionIndex}`"
|
||||
class="w-full rounded-2xl border border-default bg-surface p-5 shadow-sm transition-colors hover:border-brand-300"
|
||||
>
|
||||
<div class="mb-3 flex items-center gap-2">
|
||||
<div class="rounded-lg bg-brand-50 p-1.5 text-brand-600">
|
||||
<CalendarDays v-if="section.iconType === 'calendar'" class="h-4 w-4" />
|
||||
<Building v-else class="h-4 w-4" />
|
||||
</div>
|
||||
<h3 class="font-semibold text-secondary">{{ section.title }}</h3>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<button
|
||||
v-for="(item, questionIndex) in section.questions"
|
||||
:key="`${section.title}-${questionIndex}`"
|
||||
type="button"
|
||||
class="w-full truncate rounded-lg bg-surface-soft px-3 py-2 text-left text-xs text-secondary transition-colors hover:bg-brand-50 hover:text-brand-600 md:text-sm"
|
||||
@click="emit('select-question', item.question)"
|
||||
>
|
||||
"{{ item.question }}"
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="suggestedQuestions.length > 0">
|
||||
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
|
||||
AI
|
||||
</div>
|
||||
<h2 class="mb-6 shrink-0 text-center text-xl font-medium text-primary md:text-2xl">
|
||||
{{ $t('chat.welcomeTitle') }}
|
||||
</h2>
|
||||
|
||||
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
|
||||
<div class="mx-auto mt-2 flex w-full max-w-3xl flex-wrap justify-center gap-3">
|
||||
<button
|
||||
v-for="(item, index) in suggestedQuestions"
|
||||
:key="`${item.question}-${index}`"
|
||||
type="button"
|
||||
class="rounded-full border border-default bg-surface px-4 py-2 text-sm text-secondary shadow-sm transition-all hover:border-brand-300 hover:bg-brand-50 hover:text-brand-600"
|
||||
@click="emit('select-question', item.question)"
|
||||
>
|
||||
"{{ item.question }}"
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="mb-6 mt-2 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
|
||||
AI
|
||||
</div>
|
||||
<h2 class="text-center text-xl font-medium text-primary md:text-2xl">
|
||||
{{ $t('chat.welcomeTitle') }}
|
||||
</h2>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,398 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 单条聊天消息:用户气泡、助手 Markdown、请假/出货子组件、来源引用与操作栏。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { Check, Copy, Edit2, LayoutGrid, MessageSquareText, RotateCw } from 'lucide-vue-next';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import type { ChatMessage, SourceFileLink } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
|
||||
|
||||
export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
onMarkdownClick: (event: MouseEvent) => void;
|
||||
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
canOpenQueryPreview: (msg: ChatMessage) => boolean;
|
||||
getQueryPreviewSummary: (msg: ChatMessage) => string;
|
||||
openQueryPreviewDialog: (msg: ChatMessage) => void;
|
||||
shippingActionButtonClass: (variant?: string) => string;
|
||||
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
|
||||
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
|
||||
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
|
||||
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
|
||||
getSourceTitle: (doc: Record<string, unknown>) => string;
|
||||
getSourceMeta: (doc: Record<string, unknown>) => string;
|
||||
getSourceBrief: (doc: Record<string, unknown>) => string;
|
||||
openPreview: (file: SourceFileLink) => void;
|
||||
}
|
||||
|
||||
const {
|
||||
message,
|
||||
index,
|
||||
messageCount,
|
||||
isThinking,
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
shippingHandlers,
|
||||
} = defineProps<{
|
||||
message: ChatMessage;
|
||||
index: number;
|
||||
messageCount: number;
|
||||
isThinking: boolean;
|
||||
showChatRating: boolean;
|
||||
copiedIndex: number | null;
|
||||
isShippingNoticeAgent: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
copy: [];
|
||||
edit: [content: string];
|
||||
resend: [content: string];
|
||||
regenerate: [];
|
||||
'open-feedback': [];
|
||||
}>();
|
||||
|
||||
const isLeaveMessage = computed(() =>
|
||||
message.type === 'leave-form'
|
||||
|| message.type === 'leave-confirmation'
|
||||
|| message.type === 'leave-result',
|
||||
);
|
||||
|
||||
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
|
||||
const sourceLinks = computed(() => handlers.getSourceLinks(retrieverResources.value));
|
||||
|
||||
const showSourceSection = computed(() => {
|
||||
if (message.role !== 'assistant' || isLeaveMessage.value) return false;
|
||||
return retrieverResources.value.length > 0
|
||||
|| (message.attribution_parts?.length ?? 0) > 0
|
||||
|| sourceLinks.value.length > 0;
|
||||
});
|
||||
|
||||
const showActions = computed(() => message.type !== 'leave-form');
|
||||
const isLastMessage = computed(() => index === messageCount - 1);
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
:data-msg-index="index"
|
||||
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
|
||||
:class="message.role === 'user' ? 'justify-end' : 'justify-start'"
|
||||
>
|
||||
<div
|
||||
class="flex flex-col"
|
||||
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||||
>
|
||||
<div
|
||||
class="text-[15px] leading-relaxed"
|
||||
:class="message.role === 'user'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<div v-else>
|
||||
<LeaveMessageBlock
|
||||
v-if="isLeaveMessage"
|
||||
:message="message"
|
||||
:index="index"
|
||||
:handlers="leaveHandlers"
|
||||
/>
|
||||
<ShippingInventoryMappingMessage
|
||||
v-else-if="message.type === 'shipping-inventory-mapping' && handlers.getShippingInventoryMappingPayload(message)"
|
||||
:message="message"
|
||||
:handlers="shippingHandlers"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
|
||||
@click="handlers.onMarkdownClick"
|
||||
v-html="handlers.renderMarkdown(message.content)"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
|
||||
class="mt-4"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
|
||||
@click="handlers.openQueryPreviewDialog(message)"
|
||||
>
|
||||
<LayoutGrid class="h-3.5 w-3.5" />
|
||||
{{ handlers.getQueryPreviewSummary(message) }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isShippingNoticeAgent && message.shipping_actions?.length"
|
||||
class="mt-4 space-y-2 border-t border-default pt-4"
|
||||
>
|
||||
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(action, actionIndex) in message.shipping_actions"
|
||||
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
|
||||
type="button"
|
||||
:class="handlers.shippingActionButtonClass(action.variant)"
|
||||
:disabled="isThinking || message.shipping_actions_used"
|
||||
@click="handlers.onShippingActionClick(message, action)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showSourceSection" class="mt-2 space-y-2">
|
||||
<div v-if="sourceLinks.length > 0" class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="(file, linkIndex) in sourceLinks"
|
||||
:key="`src-link-top-${linkIndex}-${file.url}`"
|
||||
type="button"
|
||||
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="handlers.openPreview(file)"
|
||||
>
|
||||
{{ file.name }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<details
|
||||
v-if="retrieverResources.length > 0"
|
||||
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
|
||||
:open="handlers.shouldExpandSourceDetails(message)"
|
||||
>
|
||||
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
|
||||
{{ $t('chat.sourceDocs') }} ({{ retrieverResources.length }})
|
||||
</summary>
|
||||
<div class="mt-3 space-y-2">
|
||||
<div
|
||||
v-for="(doc, docIndex) in retrieverResources"
|
||||
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
|
||||
class="rounded-lg border border-default bg-surface p-3"
|
||||
>
|
||||
<div class="break-all text-sm font-semibold text-primary">{{ handlers.getSourceTitle(doc) }}</div>
|
||||
<div v-if="handlers.getSourceMeta(doc)" class="mt-1 text-xs text-muted">{{ handlers.getSourceMeta(doc) }}</div>
|
||||
<div v-if="handlers.getSourceBrief(doc)" class="mt-2 whitespace-pre-wrap break-all text-xs text-secondary">
|
||||
{{ handlers.getSourceBrief(doc) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details
|
||||
v-if="message.attribution_parts && message.attribution_parts.length > 0"
|
||||
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
|
||||
open
|
||||
>
|
||||
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
|
||||
{{ $t('chat.attributionParts') }}
|
||||
</summary>
|
||||
<ul class="mt-3 space-y-2">
|
||||
<li
|
||||
v-for="(part, partIndex) in message.attribution_parts"
|
||||
:key="`attr-${partIndex}`"
|
||||
class="rounded-lg border border-default bg-surface p-3 text-xs text-secondary"
|
||||
>
|
||||
{{ part }}
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="showActions"
|
||||
class="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100"
|
||||
:class="message.role === 'user' ? 'justify-end text-muted' : 'justify-start text-muted'"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
|
||||
:title="$t('chat.actions.copy')"
|
||||
@click.stop="emit('copy')"
|
||||
>
|
||||
<Check v-if="isCopied" class="h-3.5 w-3.5 text-emerald-500" />
|
||||
<Copy v-else class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
|
||||
<template v-if="message.role === 'user'">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
|
||||
:title="$t('chat.actions.edit')"
|
||||
@click.stop="emit('edit', message.content)"
|
||||
>
|
||||
<Edit2 class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
|
||||
:title="$t('chat.actions.resend')"
|
||||
@click.stop="emit('resend', message.content)"
|
||||
>
|
||||
<RotateCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<button
|
||||
v-if="isLastMessage && !isThinking"
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
|
||||
:title="$t('chat.actions.regenerate')"
|
||||
@click="emit('regenerate')"
|
||||
>
|
||||
<RotateCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button
|
||||
v-if="showChatRating && !isThinking && !message.rated"
|
||||
type="button"
|
||||
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
|
||||
:title="$t('chat.rate')"
|
||||
@click="emit('open-feedback')"
|
||||
>
|
||||
<MessageSquareText class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
:deep(.chat-markdown) {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-table-scroll) {
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
margin: 0.75rem 0;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .chat-table-inner) {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown table) {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown th),
|
||||
:deep(.chat-markdown td) {
|
||||
border: 1px solid rgb(226 232 240);
|
||||
padding: 0.5rem 0.75rem;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown th) {
|
||||
background: rgb(248 250 252);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown th),
|
||||
:deep(.dark .chat-markdown td) {
|
||||
border-color: rgb(51 65 85);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown th) {
|
||||
background: rgb(30 41 59);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown details) {
|
||||
margin-top: 1rem;
|
||||
border: 1px solid rgb(226 232 240);
|
||||
border-radius: 0.75rem;
|
||||
background: rgb(248 250 252 / 0.9);
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown details) {
|
||||
border-color: rgb(51 65 85);
|
||||
background: rgb(30 41 59 / 0.65);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown details summary) {
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
color: rgb(71 85 105);
|
||||
list-style-position: inside;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown details summary) {
|
||||
color: rgb(203 213 225);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown details[open] summary) {
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown details pre) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-action-trigger) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 0.2rem;
|
||||
padding: 0.1rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
border: 1px solid rgb(59 130 246 / 0.28);
|
||||
background: rgb(239 246 255);
|
||||
color: rgb(29 78 216);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-action-trigger:hover) {
|
||||
background: rgb(219 234 254);
|
||||
border-color: rgb(59 130 246 / 0.4);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-intent-highlight) {
|
||||
display: inline-block;
|
||||
margin: 0 0.2rem;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 0.5rem;
|
||||
background: rgb(254 249 195);
|
||||
color: rgb(161 98 7);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-action-trigger) {
|
||||
border-color: rgb(96 165 250 / 0.35);
|
||||
background: rgb(30 41 59);
|
||||
color: rgb(147 197 253);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
|
||||
background: rgb(30 64 175 / 0.25);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-intent-highlight) {
|
||||
background: rgb(113 63 18 / 0.45);
|
||||
color: rgb(253 224 71);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,272 @@
|
||||
/**
|
||||
* features/chat/components/messages/LeaveMessageBlock.vue
|
||||
* 请假 OA 消息 UI(表单/确认/结果)。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { Search } from 'lucide-vue-next';
|
||||
import { LEAVE_TYPES } from '../../constants/leave';
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type {
|
||||
LeaveConfirmationPayload,
|
||||
LeaveFormPayload,
|
||||
LeaveRequestFormData,
|
||||
LeaveResultPayload,
|
||||
} from '../../types/leave.types';
|
||||
|
||||
export interface LeaveMessageHandlers {
|
||||
getLeaveFormPayload: (msg: ChatMessage) => LeaveFormPayload | null;
|
||||
getLeaveConfirmationPayload: (msg: ChatMessage) => LeaveConfirmationPayload | null;
|
||||
getLeaveResultPayload: (msg: ChatMessage) => LeaveResultPayload | null;
|
||||
getLeaveAgentDisplayValue: (form: LeaveRequestFormData) => string;
|
||||
getLeaveTypeLabel: (val: string) => string;
|
||||
formatDurationLabel: (hours: number, leaveType?: string) => string;
|
||||
formatYesNoLabel: (value: 0 | 1 | null) => string;
|
||||
syncLeaveDuration: (form: LeaveRequestFormData) => void;
|
||||
openLeaveAgentDialog: (msg: ChatMessage, role?: 'agent' | 'applicant') => void;
|
||||
openOALeaveRequestDirectly: () => void;
|
||||
openOARequestDirectly: (requestId: string) => void;
|
||||
submitLeaveForm: (msg: ChatMessage) => void;
|
||||
editLeaveConfirmation: (msg: ChatMessage, index: number) => void;
|
||||
confirmLeaveSubmission: (msg: ChatMessage) => void;
|
||||
}
|
||||
|
||||
const { message, index, handlers } = defineProps<{
|
||||
message: ChatMessage;
|
||||
index: number;
|
||||
handlers: LeaveMessageHandlers;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="message.type === 'leave-form'" class="space-y-4">
|
||||
<div class="text-sm font-medium text-secondary">
|
||||
{{ $t('chat.leaveFormIntro') }} <a href="#" @click.prevent="handlers.openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">{{ $t('chat.oaLeaveDirectLink') }}</a>
|
||||
</div>
|
||||
<div v-if="handlers.getLeaveFormPayload(message)" class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveFiller') }}</span>
|
||||
<input
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.fillerName"
|
||||
type="text"
|
||||
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
|
||||
disabled
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.employeeId') }}</span>
|
||||
<input
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.employeeId"
|
||||
type="text"
|
||||
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
|
||||
disabled
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.createdAt') }}</span>
|
||||
<input
|
||||
:value="handlers.getLeaveFormPayload(message)!.form.applyTime.replace('T', ' ')"
|
||||
type="text"
|
||||
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
|
||||
disabled
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveType') }}</span>
|
||||
<select
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.leaveType"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@change="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.selectLeaveType') }}</option>
|
||||
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveApplicant') }}</span>
|
||||
<div class="relative">
|
||||
<input
|
||||
:value="handlers.getLeaveFormPayload(message)!.form.applicantName ? `${handlers.getLeaveFormPayload(message)!.form.applicantName} / ${handlers.getLeaveFormPayload(message)!.form.employeeId}` : ''"
|
||||
type="text"
|
||||
:placeholder="$t('chat.selectLeaveApplicant')"
|
||||
readonly
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@click="handlers.openLeaveAgentDialog(message, 'applicant')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@click="handlers.openLeaveAgentDialog(message, 'applicant')"
|
||||
:title="$t('chat.pickLeaveApplicant')"
|
||||
>
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveAgent') }}</span>
|
||||
<div class="relative">
|
||||
<input
|
||||
:value="handlers.getLeaveAgentDisplayValue(handlers.getLeaveFormPayload(message)!.form)"
|
||||
type="text"
|
||||
:placeholder="$t('chat.selectLeaveAgent')"
|
||||
readonly
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@click="handlers.openLeaveAgentDialog(message)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@click="handlers.openLeaveAgentDialog(message)"
|
||||
:title="$t('chat.pickLeaveAgent')"
|
||||
>
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.startTime') }}</span>
|
||||
<input
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.startTime"
|
||||
type="datetime-local"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@input="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.endTime') }}</span>
|
||||
<input
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.endTime"
|
||||
type="datetime-local"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
@input="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.duration') }}</span>
|
||||
<input
|
||||
:value="handlers.formatDurationLabel(handlers.getLeaveFormPayload(message)!.form.durationHours, handlers.getLeaveFormPayload(message)!.form.leaveType)"
|
||||
type="text"
|
||||
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
|
||||
disabled
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.isOutOfOffice') }}</span>
|
||||
<select
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.isOutOfOffice"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
>
|
||||
<option :value="1">{{ $t('chat.no') }}</option>
|
||||
<option :value="0">{{ $t('chat.yes') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.isWorkInjury') }}</span>
|
||||
<select
|
||||
v-model="handlers.getLeaveFormPayload(message)!.form.isWorkInjury"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
|
||||
>
|
||||
<option :value="1">{{ $t('chat.no') }}</option>
|
||||
<option :value="0">{{ $t('chat.yes') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div v-if="handlers.getLeaveFormPayload(message)?.confirmationGenerated" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700">
|
||||
{{ $t('chat.leaveConfirmGenerated') }}
|
||||
</div>
|
||||
<div class="flex justify-end">
|
||||
<button
|
||||
@click="handlers.submitLeaveForm(message)"
|
||||
:disabled="handlers.getLeaveFormPayload(message)?.submitting || handlers.getLeaveFormPayload(message)?.confirmationGenerated"
|
||||
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{{ handlers.getLeaveFormPayload(message)?.submitting ? $t('chat.submitting') : $t('chat.submit') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="message.type === 'leave-confirmation' && handlers.getLeaveConfirmationPayload(message)" class="space-y-4">
|
||||
<div class="text-sm font-medium text-secondary">{{ message.content }}</div>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft/90 p-4">
|
||||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveFillerInfo') }}</div>
|
||||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||||
<div><span class="text-muted">{{ $t('chat.leaveFiller') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerName || $t('chat.noData') }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.createdAt') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applyTime.replace('T', ' ') }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitle"><span class="text-muted">{{ $t('chat.leaveFillerTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitle }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentId"><span class="text-muted">{{ $t('chat.leaveFillerDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentId }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveFillerCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyId1 }}</div>
|
||||
</div>
|
||||
<div class="my-3 border-t border-default"></div>
|
||||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveApplicantInfo') }}</div>
|
||||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||||
<div><span class="text-muted">{{ $t('chat.leaveApplicant') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantName }}({{ handlers.getLeaveConfirmationPayload(message)!.form.employeeId }})</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitle"><span class="text-muted">{{ $t('chat.leaveApplicantTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitle }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentId"><span class="text-muted">{{ $t('chat.leaveApplicantDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentId }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveApplicantCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyId1 }}</div>
|
||||
</div>
|
||||
<div class="my-3 border-t border-default"></div>
|
||||
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveInfo') }}</div>
|
||||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||||
<div><span class="text-muted">{{ $t('chat.leaveAgent') }}:</span>{{ handlers.getLeaveAgentDisplayValue(handlers.getLeaveConfirmationPayload(message)!.form) || $t('chat.notSelected') }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitle"><span class="text-muted">{{ $t('chat.leaveAgentTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitle }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentId"><span class="text-muted">{{ $t('chat.leaveAgentDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentId }}</div>
|
||||
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveAgentCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyId1 }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.leaveType') }}:</span>{{ handlers.getLeaveTypeLabel(handlers.getLeaveConfirmationPayload(message)!.form.leaveType) }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.duration') }}:</span>{{ handlers.formatDurationLabel(handlers.getLeaveConfirmationPayload(message)!.form.durationHours, handlers.getLeaveConfirmationPayload(message)!.form.leaveType) }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.startTime') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.startTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.endTime') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.endTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.isOutOfOffice') }}:</span>{{ handlers.formatYesNoLabel(handlers.getLeaveConfirmationPayload(message)!.form.isOutOfOffice) }}</div>
|
||||
<div><span class="text-muted">{{ $t('chat.isWorkInjury') }}:</span>{{ handlers.formatYesNoLabel(handlers.getLeaveConfirmationPayload(message)!.form.isWorkInjury) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3">
|
||||
<button
|
||||
v-if="!handlers.getLeaveConfirmationPayload(message)?.submitting && !handlers.getLeaveConfirmationPayload(message)?.confirmed"
|
||||
@click="handlers.editLeaveConfirmation(message, index)"
|
||||
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{{ $t('chat.backToEdit') }}
|
||||
</button>
|
||||
<button
|
||||
@click="handlers.confirmLeaveSubmission(message)"
|
||||
:disabled="handlers.getLeaveConfirmationPayload(message)?.submitting || handlers.getLeaveConfirmationPayload(message)?.confirmed"
|
||||
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{{ handlers.getLeaveConfirmationPayload(message)?.submitting ? $t('chat.confirming') : (handlers.getLeaveConfirmationPayload(message)?.confirmed ? $t('chat.confirmed') : $t('chat.confirm')) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="message.type === 'leave-result' && handlers.getLeaveResultPayload(message)" class="space-y-3">
|
||||
<div
|
||||
class="rounded-2xl border px-4 py-4"
|
||||
:class="handlers.getLeaveResultPayload(message)!.success
|
||||
? 'border-emerald-200 bg-emerald-50 text-emerald-800'
|
||||
: 'border-rose-200 bg-rose-50 text-rose-800'"
|
||||
>
|
||||
<div class="text-sm font-semibold">{{ handlers.getLeaveResultPayload(message)!.success ? $t('chat.oaSubmitResult') : $t('chat.oaSubmitFailed') }}</div>
|
||||
<div v-if="handlers.getLeaveResultPayload(message)!.success" class="mt-2 whitespace-pre-wrap text-sm leading-7">
|
||||
{{ $t('chat.leaveResultPrefix') }}
|
||||
<a
|
||||
href="#"
|
||||
@click.prevent="handlers.openOARequestDirectly(handlers.getLeaveResultPayload(message)!.referenceNo)"
|
||||
class="ml-1 inline-flex items-center rounded-full border border-brand-200 bg-brand-50 px-3 py-0.5 font-bold text-brand-700 transition hover:bg-brand-100 hover:underline"
|
||||
>
|
||||
{{ $t('chat.leaveResultLinkText') }}
|
||||
</a>
|
||||
</div>
|
||||
<div v-else class="mt-2 whitespace-pre-wrap text-sm leading-7">{{ message.content }}</div>
|
||||
<div class="mt-3 text-xs opacity-80">{{ $t('chat.requestNo') }}:{{ handlers.getLeaveResultPayload(message)!.referenceNo }}</div>
|
||||
<div class="mt-1 text-xs opacity-80">{{ $t('chat.submitTime') }}:{{ handlers.getLeaveResultPayload(message)!.submittedAt }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* features/chat/components/messages/ShippingInventoryMappingMessage.vue
|
||||
* 出货 Agent:库存 Excel 列映射表单消息 UI。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
|
||||
|
||||
export interface ShippingMappingHandlers {
|
||||
getPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
normalizeHeader: (header: string) => string;
|
||||
hasSampleRows: (msg: ChatMessage) => boolean;
|
||||
getSampleRowText: (msg: ChatMessage) => string;
|
||||
reupload: (msg: ChatMessage) => void;
|
||||
apply: (msg: ChatMessage) => void;
|
||||
}
|
||||
|
||||
const { message, handlers } = defineProps<{
|
||||
message: ChatMessage;
|
||||
handlers: ShippingMappingHandlers;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="handlers.getPayload(message)" class="space-y-4">
|
||||
<div class="whitespace-pre-wrap text-sm font-medium text-secondary">{{ message.content }}</div>
|
||||
<div class="space-y-4 rounded-2xl border border-default bg-surface-soft/90 p-4">
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.inventoryHeaders') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.headerRow', { row: handlers.getPayload(message)!.schema_preview.header_row_index || 1 }) }}
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span
|
||||
v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])"
|
||||
:key="`inv-h-${h}`"
|
||||
class="rounded-full border border-default bg-surface px-3 py-1 text-xs text-secondary"
|
||||
>{{ handlers.normalizeHeader(h) || $t('chat.shippingNoticeMapping.empty') }}</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="handlers.hasSampleRows(message)"
|
||||
class="whitespace-pre-wrap text-xs text-muted"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeMapping.sample') }}:{{ handlers.getSampleRowText(message) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: handlers.getPayload(message)!.order.skus.length, skus: handlers.getPayload(message)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.sku"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.availableQtyColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.available_qty"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`qty-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.reservation_id"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
@click="handlers.reupload(message)"
|
||||
>
|
||||
{{ $t('chat.shippingNoticeMapping.reupload') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
@click="handlers.apply(message)"
|
||||
>
|
||||
{{ handlers.getPayload(message)!.applying ? $t('chat.shippingNoticeMapping.applying') : $t('chat.shippingNoticeMapping.applyAndParse') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* features/chat/composables/chat.context.ts
|
||||
* 对话页 provide/inject 上下文类型与注入 key。
|
||||
*
|
||||
* provide 时使用 `reactive(useChatPage())`,嵌套 Ref/ComputedRef 在消费侧自动解包,
|
||||
* template 与 script 均可直接 `page.input` / `page.isThinking` 而无需 `.value`。
|
||||
*/
|
||||
import { inject, type InjectionKey, type Reactive, type UnwrapNestedRefs } from 'vue';
|
||||
import type { useChatPage } from './useChatPage';
|
||||
|
||||
/** useChatPage() 原始返回(含 Ref/ComputedRef) */
|
||||
export type ChatPageContext = ReturnType<typeof useChatPage>;
|
||||
|
||||
/** ChatView provide 后经 reactive() 包装、供子组件 inject 的类型 */
|
||||
export type ChatPageContextProvided = Reactive<UnwrapNestedRefs<ChatPageContext>>;
|
||||
|
||||
export const CHAT_PAGE_KEY: InjectionKey<ChatPageContextProvided> = Symbol('chatPage');
|
||||
|
||||
/**
|
||||
* 在 ChatView 子树中获取对话页上下文。
|
||||
* 必须在已 provide(CHAT_PAGE_KEY) 的组件树内调用。
|
||||
*/
|
||||
export function useChatPageContext(): ChatPageContextProvided {
|
||||
const ctx = inject(CHAT_PAGE_KEY);
|
||||
if (!ctx) {
|
||||
throw new Error('[chat] useChatPageContext() must be used inside ChatView (provide CHAT_PAGE_KEY)');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/chat.deps.ts
|
||||
* 聊天 composables 共享依赖。
|
||||
*/
|
||||
import type { WritableComputedRef } from 'vue';
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
|
||||
import type { useMessage } from '@/composables/useMessage';
|
||||
import type { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
export interface ChatDeps {
|
||||
t: ComposerTranslation;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChat.ts
|
||||
* SSE 流式对话核心:消息列表、runs、发送与接收。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { getAuthHeaders } from '@/utils/auth';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
|
||||
|
||||
const normalizeResources = (resources: unknown) => {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAgent.ts
|
||||
* 当前 Agent 元数据、知识库选项、推荐问题与用户可切换 Agent 列表。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
|
||||
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import type { UseChatGuidesReturn } from './useChatGuides';
|
||||
|
||||
export type AgentSuggestedQuestionItem = {
|
||||
question: string;
|
||||
group: string;
|
||||
};
|
||||
|
||||
const DEFAULT_KB = '企业知识库';
|
||||
const ERP_KB = 'ERP知识库';
|
||||
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
|
||||
|
||||
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
|
||||
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
|
||||
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
|
||||
};
|
||||
|
||||
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
|
||||
人事规章: {
|
||||
style: 'styled',
|
||||
questions: [
|
||||
{ question: '查询我有多少假期?', group: '考勤与休假' },
|
||||
{ question: '如何进行请假?', group: '考勤与休假' },
|
||||
{ question: '查公司法定节假日?', group: '考勤与休假' },
|
||||
{ question: '新员工入职须知', group: '规章与日常' },
|
||||
{ question: '怎么开具在职证明?', group: '规章与日常' },
|
||||
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
|
||||
],
|
||||
},
|
||||
通用入口: {
|
||||
style: 'plain',
|
||||
questions: [
|
||||
{ question: '新员工入职须知', group: '' },
|
||||
{ question: '查询我有多少假期?', group: '' },
|
||||
{ question: '如何进行请假?', group: '' },
|
||||
{ question: '查公司法定节假日?', group: '' },
|
||||
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => {
|
||||
if (typeof item === 'string') {
|
||||
const question = item.trim();
|
||||
return question ? { question, group: '' } : null;
|
||||
}
|
||||
if (!item || typeof item !== 'object') return null;
|
||||
const record = item as Record<string, unknown>;
|
||||
const question = String(record.question || record.text || '').trim();
|
||||
const group = String(record.group || '').trim();
|
||||
return question ? { question, group } : null;
|
||||
})
|
||||
.filter((item): item is AgentSuggestedQuestionItem => !!item);
|
||||
};
|
||||
|
||||
export interface UseChatAgentOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
|
||||
}
|
||||
|
||||
export function useChatAgent(options: UseChatAgentOptions) {
|
||||
const { deps, currentAgentId, chatGuides } = options;
|
||||
const { t, msg, router } = deps;
|
||||
|
||||
const currentAgent = ref<any>(null);
|
||||
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
|
||||
const showAgentPanel = ref(true);
|
||||
const selectedKb = ref(DEFAULT_KB);
|
||||
const kbOptions = [DEFAULT_KB, ERP_KB];
|
||||
|
||||
const getKbLabel = (kb: string) => {
|
||||
if (kb === DEFAULT_KB) return t('chat.kb.enterprise');
|
||||
if (kb === ERP_KB) return t('chat.kb.erp');
|
||||
return kb;
|
||||
};
|
||||
|
||||
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
|
||||
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
|
||||
const availableKbOptions = computed(() => (
|
||||
canSelectErpKnowledgeBase.value
|
||||
? kbOptions
|
||||
: kbOptions.filter((option) => option !== ERP_KB)
|
||||
));
|
||||
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
|
||||
|
||||
watch(canSelectErpKnowledgeBase, (allowed) => {
|
||||
if (allowed) {
|
||||
selectedKb.value = ERP_KB;
|
||||
return;
|
||||
}
|
||||
if (selectedKb.value === ERP_KB) {
|
||||
selectedKb.value = DEFAULT_KB;
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
const agentDescription = computed(() => {
|
||||
const text = String(currentAgent.value?.description || '').trim();
|
||||
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
|
||||
});
|
||||
|
||||
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
|
||||
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
|
||||
if (style === 'styled') return 'styled';
|
||||
if (style === 'plain') return 'plain';
|
||||
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
|
||||
});
|
||||
|
||||
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
|
||||
const configured = normalizeAgentSuggestedQuestions(
|
||||
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
|
||||
);
|
||||
if (configured.length > 0) return configured;
|
||||
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
|
||||
});
|
||||
|
||||
const styledSuggestedQuestionSections = computed(() => {
|
||||
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
|
||||
for (const item of agentSuggestedQuestions.value) {
|
||||
const groupName = String(item.group || '').trim() || '常见问题';
|
||||
if (!groups.has(groupName)) {
|
||||
groups.set(groupName, []);
|
||||
}
|
||||
groups.get(groupName)?.push(item);
|
||||
}
|
||||
const iconTypes: Array<'calendar' | 'building'> = ['calendar', 'building'];
|
||||
return Array.from(groups.entries()).map(([title, questions], index) => ({
|
||||
title,
|
||||
questions,
|
||||
iconType: iconTypes[index % iconTypes.length] as 'calendar' | 'building',
|
||||
}));
|
||||
});
|
||||
|
||||
const loadAgent = async () => {
|
||||
try {
|
||||
currentAgent.value = await getUserAgent(currentAgentId.value);
|
||||
await chatGuides.loadGuides();
|
||||
} catch (e) {
|
||||
if (e instanceof BusinessError && e.status === 403) {
|
||||
msg.error(t('workspace.permission.denied') || 'Access denied');
|
||||
router.push('/workspace?no_redirect=1');
|
||||
return;
|
||||
}
|
||||
console.error('Failed to load agent', e);
|
||||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||||
chatGuides.clearGuides();
|
||||
}
|
||||
};
|
||||
|
||||
const loadUserAgents = async () => {
|
||||
try {
|
||||
const agents = await listUserAgents();
|
||||
userAgents.value = Array.isArray(agents)
|
||||
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
|
||||
: [];
|
||||
if (userAgents.value.length === 0) {
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
} catch {
|
||||
userAgents.value = [];
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const switchToAgent = (agent: { id: number; name: string }) => {
|
||||
if (agent.id === currentAgentId.value) return;
|
||||
setLastChatAgentId(agent.id);
|
||||
router.push(`/chat/${agent.id}`);
|
||||
};
|
||||
|
||||
return {
|
||||
currentAgent,
|
||||
userAgents,
|
||||
showAgentPanel,
|
||||
selectedKb,
|
||||
getKbLabel,
|
||||
availableKbOptions,
|
||||
kbDropdownDisabled,
|
||||
agentDescription,
|
||||
suggestedQuestionsStyle,
|
||||
agentSuggestedQuestions,
|
||||
styledSuggestedQuestionSections,
|
||||
loadAgent,
|
||||
loadUserAgents,
|
||||
switchToAgent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAttachments.ts
|
||||
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef, type Ref } from 'vue';
|
||||
import { uploadChatFile } from '../api/chat.api';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
export type ChatUploadFileSpec =
|
||||
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string };
|
||||
|
||||
const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<string>> = {
|
||||
document: new Set([
|
||||
'txt', 'md', 'markdown', 'mdx', 'pdf', 'html', 'htm', 'xlsx', 'xls', 'vtt', 'properties',
|
||||
'doc', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub',
|
||||
]),
|
||||
image: new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']),
|
||||
audio: new Set(['mp3', 'm4a', 'wav', 'webm', 'mpga']),
|
||||
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
|
||||
};
|
||||
|
||||
const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
const idx = withoutQuery.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return withoutQuery.slice(idx + 1).trim();
|
||||
};
|
||||
|
||||
const isKnownDifyExt = (ext: string) => {
|
||||
if (!ext) return false;
|
||||
return (
|
||||
DIFY_SUPPORTED_EXTS.image.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.document.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.audio.has(ext)
|
||||
|| DIFY_SUPPORTED_EXTS.video.has(ext)
|
||||
);
|
||||
};
|
||||
|
||||
const resolveDifyType = (ext: string, mime?: string): Exclude<ChatUploadFileType, 'custom'> | null => {
|
||||
const m = (mime || '').toLowerCase();
|
||||
if (m.startsWith('image/')) return 'image';
|
||||
if (m.startsWith('audio/')) return 'audio';
|
||||
if (m.startsWith('video/')) return 'video';
|
||||
if (DIFY_SUPPORTED_EXTS.image.has(ext)) return 'image';
|
||||
if (DIFY_SUPPORTED_EXTS.document.has(ext)) return 'document';
|
||||
const inAudio = DIFY_SUPPORTED_EXTS.audio.has(ext);
|
||||
const inVideo = DIFY_SUPPORTED_EXTS.video.has(ext);
|
||||
if (inAudio && !inVideo) return 'audio';
|
||||
if (inVideo) return 'video';
|
||||
return null;
|
||||
};
|
||||
|
||||
export interface UseChatAttachmentsOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
currentAgent: Ref<any>;
|
||||
}
|
||||
|
||||
export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const { deps, currentAgentId, currentAgent } = options;
|
||||
const { msg } = deps;
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const isUploadingAttachments = ref(false);
|
||||
|
||||
const difyFileUploadConfig = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.file_upload as any) || {};
|
||||
});
|
||||
|
||||
const difySystemParameters = computed<Record<string, any>>(() => {
|
||||
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
|
||||
});
|
||||
|
||||
const attachmentPolicy = computed(() => {
|
||||
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
|
||||
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
|
||||
image: { local: false, remote: false },
|
||||
document: { local: false, remote: false },
|
||||
audio: { local: false, remote: false },
|
||||
video: { local: false, remote: false },
|
||||
custom: { local: false, remote: false },
|
||||
};
|
||||
const raw = difyFileUploadConfig.value as any;
|
||||
const normalizedAllowedExts = Array.isArray(raw?.allowed_file_extensions)
|
||||
? raw.allowed_file_extensions
|
||||
.map((v: any) => String(v || '').trim())
|
||||
.filter(Boolean)
|
||||
.map((v: string) => (v.startsWith('.') ? v.slice(1) : v).toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedExts: Set<string> | null = normalizedAllowedExts.length > 0 ? new Set<string>(normalizedAllowedExts) : null;
|
||||
|
||||
const allowedTypes = Array.isArray(raw?.allowed_file_types)
|
||||
? raw.allowed_file_types
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedTypeSet = allowedTypes.length > 0 ? new Set(allowedTypes) : null;
|
||||
|
||||
const allowedMethods = Array.isArray(raw?.allowed_file_upload_methods)
|
||||
? raw.allowed_file_upload_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const allowedMethodSet = allowedMethods.length > 0 ? new Set(allowedMethods) : null;
|
||||
|
||||
const isNewSchema = Boolean(raw && raw.enabled === true && allowedTypeSet && allowedMethodSet);
|
||||
if (isNewSchema && allowedTypeSet && allowedMethodSet) {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
const cfgEnabled = typeof cfg?.enabled === 'boolean' ? Boolean(cfg.enabled) : null;
|
||||
const typeAllowed = allowedTypeSet.has(t);
|
||||
if (cfgEnabled === false) continue;
|
||||
if (cfgEnabled !== true && !typeAllowed) continue;
|
||||
|
||||
const transferMethods = Array.isArray(cfg?.transfer_methods)
|
||||
? cfg.transfer_methods
|
||||
.map((v: any) => String(v || '').trim().toLowerCase())
|
||||
.filter(Boolean)
|
||||
: [];
|
||||
const methodSet = transferMethods.length > 0 ? new Set(transferMethods) : allowedMethodSet;
|
||||
|
||||
enabled[t] = {
|
||||
local: methodSet.has('local_file'),
|
||||
remote: methodSet.has('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg?.number_limits))
|
||||
? Number(cfg.number_limits)
|
||||
: (Number.isFinite(Number(raw?.number_limits)) ? Number(raw.number_limits) : undefined),
|
||||
};
|
||||
}
|
||||
} else {
|
||||
for (const t of types) {
|
||||
const cfg = raw?.[t];
|
||||
if (!cfg || !cfg.enabled) continue;
|
||||
const transferMethods = Array.isArray(cfg.transfer_methods) ? cfg.transfer_methods : [];
|
||||
enabled[t] = {
|
||||
local: transferMethods.includes('local_file'),
|
||||
remote: transferMethods.includes('remote_url'),
|
||||
limit: Number.isFinite(Number(cfg.number_limits)) ? Number(cfg.number_limits) : undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mergedLimits = {
|
||||
...(difySystemParameters.value || {}),
|
||||
...(raw?.fileUploadConfig || {}),
|
||||
} as any;
|
||||
const system = mergedLimits || {};
|
||||
const sizeLimitMb: Record<ChatUploadFileType, number | null> = {
|
||||
image: Number.isFinite(Number(system.image_file_size_limit)) ? Number(system.image_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
audio: Number.isFinite(Number(system.audio_file_size_limit)) ? Number(system.audio_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
video: Number.isFinite(Number(system.video_file_size_limit)) ? Number(system.video_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
|
||||
document: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
custom: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
|
||||
};
|
||||
|
||||
const anyEnabled = Object.values(enabled).some((v) => v.local || v.remote);
|
||||
const canLocal = Object.values(enabled).some((v) => v.local);
|
||||
const canRemote = Object.values(enabled).some((v) => v.remote);
|
||||
const totalLimit = (() => {
|
||||
const v1 = raw?.fileUploadConfig?.file_upload_limit;
|
||||
if (Number.isFinite(Number(v1))) return Number(v1);
|
||||
const v2 = raw?.number_limits;
|
||||
if (Number.isFinite(Number(v2))) return Number(v2);
|
||||
return null;
|
||||
})();
|
||||
|
||||
const effectiveAllowedExts: Set<string> | null = (() => {
|
||||
if (!allowedExts) return null;
|
||||
const filtered = new Set<string>();
|
||||
for (const ext of allowedExts) {
|
||||
const t = resolveDifyType(ext);
|
||||
if (!t) {
|
||||
if (enabled.custom.local || enabled.custom.remote) filtered.add(ext);
|
||||
continue;
|
||||
}
|
||||
if (enabled[t]?.local || enabled[t]?.remote) filtered.add(ext);
|
||||
}
|
||||
return filtered.size > 0 ? filtered : null;
|
||||
})();
|
||||
|
||||
const accept = (() => {
|
||||
if (enabled.custom.local) return '';
|
||||
if (effectiveAllowedExts) {
|
||||
return Array.from(effectiveAllowedExts).map((e) => `.${e}`).join(',');
|
||||
}
|
||||
const parts = new Set<string>();
|
||||
const pushExts = (exts: Set<string>) => {
|
||||
for (const e of exts) parts.add(`.${e}`);
|
||||
};
|
||||
if (enabled.image.local) pushExts(DIFY_SUPPORTED_EXTS.image);
|
||||
if (enabled.audio.local) pushExts(DIFY_SUPPORTED_EXTS.audio);
|
||||
if (enabled.video.local) pushExts(DIFY_SUPPORTED_EXTS.video);
|
||||
if (enabled.document.local) pushExts(DIFY_SUPPORTED_EXTS.document);
|
||||
return Array.from(parts).join(',');
|
||||
})();
|
||||
|
||||
return {
|
||||
anyEnabled,
|
||||
enabled,
|
||||
sizeLimitMb,
|
||||
canLocal,
|
||||
canRemote,
|
||||
accept,
|
||||
allowedExts: effectiveAllowedExts,
|
||||
totalLimit,
|
||||
};
|
||||
});
|
||||
|
||||
const inferFileTypeFromUrl = (url: string): ChatUploadFileType | null => resolveDifyType(extractExt(url));
|
||||
|
||||
const inferFileTypeFromFile = (file: File): ChatUploadFileType | null => {
|
||||
const ext = extractExt(file.name || '');
|
||||
return resolveDifyType(ext, file.type || '');
|
||||
};
|
||||
|
||||
const removeAttachment = (id: string) => {
|
||||
attachments.value = attachments.value.filter((a) => a.id !== id);
|
||||
};
|
||||
|
||||
const handleLocalFilesSelected = (event: Event) => {
|
||||
const inputEl = event.target as HTMLInputElement | null;
|
||||
const fileList = inputEl?.files;
|
||||
if (!fileList) return;
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
|
||||
}
|
||||
if (inputEl) inputEl.value = '';
|
||||
};
|
||||
|
||||
const addRemoteUrlAttachment = (urlFromInput?: string) => {
|
||||
const raw = (urlFromInput ?? '').trim();
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
if (!type) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
|
||||
if (!attachmentPolicy.value.anyEnabled) return [];
|
||||
if (attachments.value.length === 0) return [];
|
||||
|
||||
const specs: ChatUploadFileSpec[] = [];
|
||||
const locals = attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
|
||||
const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array<Extract<PendingAttachment, { kind: 'remote' }>>;
|
||||
|
||||
if (locals.length > 0) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
for (const item of remotes) {
|
||||
specs.push({ type: item.type, transfer_method: 'remote_url', url: item.url });
|
||||
}
|
||||
|
||||
return specs;
|
||||
};
|
||||
|
||||
const clearAttachments = () => {
|
||||
attachments.value = [];
|
||||
};
|
||||
|
||||
return {
|
||||
attachments,
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
removeAttachment,
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
clearAttachments,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* features/chat/composables/useChatBrowserPanel.ts
|
||||
* 内置浏览器侧栏:URL 规范化、iframe 加载与桌面端宽度拖拽。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
const MIN_BROWSER_PANEL_WIDTH = 320;
|
||||
const MAX_BROWSER_PANEL_WIDTH = 960;
|
||||
|
||||
export interface UseChatBrowserPanelOptions {
|
||||
/** 无效 URL 等提示 */
|
||||
warn: (message: string) => void;
|
||||
invalidUrlMessage: string;
|
||||
enterUrlMessage: string;
|
||||
}
|
||||
|
||||
const normalizeBrowserInput = (value: string) => {
|
||||
const raw = (value || '').trim();
|
||||
if (!raw) return '';
|
||||
if (/^https?:\/\//i.test(raw)) return raw;
|
||||
if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`;
|
||||
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`;
|
||||
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`;
|
||||
return '';
|
||||
};
|
||||
|
||||
export function useChatBrowserPanel(options: UseChatBrowserPanelOptions) {
|
||||
const open = ref(false);
|
||||
const draftUrl = ref('');
|
||||
const currentUrl = ref('');
|
||||
const frameKey = ref(0);
|
||||
const panelWidth = ref(420);
|
||||
const isResizing = ref(false);
|
||||
const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth);
|
||||
|
||||
const clampPanelWidth = (width: number) => {
|
||||
const maxAllowed = Math.min(
|
||||
MAX_BROWSER_PANEL_WIDTH,
|
||||
Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7)),
|
||||
);
|
||||
return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed);
|
||||
};
|
||||
|
||||
const panelStyle = computed(() => {
|
||||
if (viewportWidth.value < 1024) return undefined;
|
||||
return { width: `${panelWidth.value}px` };
|
||||
});
|
||||
|
||||
const loadPage = () => {
|
||||
const normalized = normalizeBrowserInput(draftUrl.value);
|
||||
if (!normalized) {
|
||||
options.warn(options.invalidUrlMessage);
|
||||
return;
|
||||
}
|
||||
currentUrl.value = normalized;
|
||||
draftUrl.value = normalized;
|
||||
frameKey.value += 1;
|
||||
open.value = true;
|
||||
};
|
||||
|
||||
const refreshPage = () => {
|
||||
if (!currentUrl.value) {
|
||||
loadPage();
|
||||
return;
|
||||
}
|
||||
frameKey.value += 1;
|
||||
};
|
||||
|
||||
const openInNewTab = () => {
|
||||
const normalized = currentUrl.value || normalizeBrowserInput(draftUrl.value);
|
||||
if (!normalized) {
|
||||
options.warn(options.enterUrlMessage);
|
||||
return;
|
||||
}
|
||||
window.open(normalized, '_blank', 'noopener,noreferrer');
|
||||
};
|
||||
|
||||
const onUrlEnter = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Enter') return;
|
||||
event.preventDefault();
|
||||
loadPage();
|
||||
};
|
||||
|
||||
const handleResizeMove = (event: MouseEvent) => {
|
||||
if (!isResizing.value) return;
|
||||
panelWidth.value = clampPanelWidth(window.innerWidth - event.clientX);
|
||||
};
|
||||
|
||||
const stopResize = () => {
|
||||
if (!isResizing.value) return;
|
||||
isResizing.value = false;
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
window.removeEventListener('mousemove', handleResizeMove);
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
const startResize = (event: MouseEvent) => {
|
||||
if (viewportWidth.value < 1024) return;
|
||||
event.preventDefault();
|
||||
isResizing.value = true;
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
window.addEventListener('mousemove', handleResizeMove);
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
const syncViewportWidth = () => {
|
||||
viewportWidth.value = window.innerWidth;
|
||||
if (viewportWidth.value >= 1024) {
|
||||
panelWidth.value = clampPanelWidth(panelWidth.value);
|
||||
}
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
open.value = false;
|
||||
};
|
||||
|
||||
const toggle = () => {
|
||||
open.value = !open.value;
|
||||
};
|
||||
|
||||
return {
|
||||
open,
|
||||
draftUrl,
|
||||
currentUrl,
|
||||
frameKey,
|
||||
panelStyle,
|
||||
isResizing,
|
||||
loadPage,
|
||||
refreshPage,
|
||||
openInNewTab,
|
||||
onUrlEnter,
|
||||
startResize,
|
||||
stopResize,
|
||||
syncViewportWidth,
|
||||
close,
|
||||
toggle,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* features/chat/composables/useChatGuides.ts
|
||||
* Agent 学习之窗:指南列表加载与弹窗状态。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef } from 'vue';
|
||||
import { listAgentGuides } from '@/features/auth/api/user.api';
|
||||
|
||||
export interface AgentGuide {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
file_url?: string;
|
||||
file_path?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
export interface UseChatGuidesOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function useChatGuides(options: UseChatGuidesOptions) {
|
||||
const { currentAgentId } = options;
|
||||
|
||||
const guides = ref<AgentGuide[]>([]);
|
||||
const showModal = ref(false);
|
||||
const activeGuideId = ref<number | null>(null);
|
||||
const showSidebar = ref(true);
|
||||
|
||||
const activeGuide = computed(() => guides.value.find((g) => g.id === activeGuideId.value));
|
||||
|
||||
const loadGuides = async () => {
|
||||
try {
|
||||
const res = await listAgentGuides(currentAgentId.value || 0);
|
||||
guides.value = Array.isArray(res) ? (res as AgentGuide[]) : [];
|
||||
} catch (error) {
|
||||
console.error('Failed to load agent guides:', error);
|
||||
guides.value = [];
|
||||
}
|
||||
};
|
||||
|
||||
const clearGuides = () => {
|
||||
guides.value = [];
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
const first = guides.value[0];
|
||||
if (!first) return;
|
||||
activeGuideId.value = first.id;
|
||||
showModal.value = true;
|
||||
showSidebar.value = true;
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
showModal.value = false;
|
||||
};
|
||||
|
||||
return {
|
||||
guides,
|
||||
showModal,
|
||||
activeGuideId,
|
||||
activeGuide,
|
||||
showSidebar,
|
||||
loadGuides,
|
||||
clearGuides,
|
||||
openModal,
|
||||
closeModal,
|
||||
};
|
||||
}
|
||||
|
||||
export type UseChatGuidesReturn = ReturnType<typeof useChatGuides>;
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChatHistory.ts
|
||||
* 跨 Agent 聊天历史列表(工作台 History 页 / 移动端 Tab)。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { getAuthHeaders } from '@/utils/auth';
|
||||
import { requestJson } from '@/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type { ChatCrossAgentHistoryItem } from '../types/chat.types';
|
||||
|
||||
export function useChatHistory() {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* features/chat/composables/useChatLeave.ts
|
||||
* 请假(OA)编排层:组合 leave/* 子模块,对外暴露 ChatView 所需 API。
|
||||
*
|
||||
* 消息类型约定(写入 messages 列表):
|
||||
* - leave-form:可编辑表单
|
||||
* - leave-confirmation:提交前确认
|
||||
* - leave-result:OA 提交结果
|
||||
*/
|
||||
import { computed, type ComputedRef, type Ref } from 'vue';
|
||||
import { getUserProfile } from '@/features/auth/api/user.api';
|
||||
import { LEAVE_FEATURE_AGENT_NAMES, LEAVE_TYPES } from '../constants/leave';
|
||||
import {
|
||||
createLeaveAgentPickerApi,
|
||||
createLeaveFlowApi,
|
||||
createLeaveFormApi,
|
||||
createLeaveLocalMessageApi,
|
||||
createLeaveOaLoginApi,
|
||||
formatDurationLabel,
|
||||
formatYesNoLabel,
|
||||
getLeaveAgentDisplayValue,
|
||||
getLeaveConfirmationPayload,
|
||||
getLeaveFormPayload,
|
||||
getLeaveResultPayload,
|
||||
syncLeaveDuration,
|
||||
} from '../leave';
|
||||
import { getLeaveTypeLabel } from '../leave/leaveDisplay';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
export interface UseChatLeaveOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgent: Ref<{ name?: string } | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
currentUser: Ref<Record<string, unknown> | null>;
|
||||
currentUserDisplayName: ComputedRef<string>;
|
||||
currentUserEmployeeId: ComputedRef<string>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
}
|
||||
|
||||
export function useChatLeave(options: UseChatLeaveOptions) {
|
||||
const {
|
||||
deps: { t, msg },
|
||||
currentAgent,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
} = options;
|
||||
|
||||
const canUseLeaveFeature = computed(() =>
|
||||
LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()),
|
||||
);
|
||||
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createLeaveLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
});
|
||||
|
||||
const oaLogin = createLeaveOaLoginApi({
|
||||
currentUserEmployeeId,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const agentPicker = createLeaveAgentPickerApi({
|
||||
currentAgentId,
|
||||
messages,
|
||||
saveLocalMessageToBackend,
|
||||
});
|
||||
|
||||
const formApi = createLeaveFormApi({
|
||||
messages,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const flowApi = createLeaveFlowApi({
|
||||
canUseLeaveFeature,
|
||||
isThinking,
|
||||
messages,
|
||||
conversationId,
|
||||
history,
|
||||
currentAgentId,
|
||||
loadHistory,
|
||||
newLocalMessageId,
|
||||
saveLocalMessageToBackend,
|
||||
createLeaveFormData: formApi.createLeaveFormData,
|
||||
checkLeaveBalance: formApi.checkLeaveBalance,
|
||||
formatLeaveBalanceNumber: formApi.formatLeaveBalanceNumber,
|
||||
msg,
|
||||
t,
|
||||
});
|
||||
|
||||
const syncCurrentUserProfile = async () => {
|
||||
if (currentUser.value?.real_name && String(currentUser.value.real_name).trim()) return;
|
||||
try {
|
||||
const data = await getUserProfile();
|
||||
currentUser.value = { ...currentUser.value, ...data };
|
||||
} catch (e) {
|
||||
console.error('Failed to load current user profile', e);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
LEAVE_TYPES,
|
||||
canUseLeaveFeature,
|
||||
...oaLogin,
|
||||
...agentPicker,
|
||||
getLeaveTypeLabel,
|
||||
formatDurationLabel: (hours: number, leaveType?: string) => formatDurationLabel(hours, leaveType, t),
|
||||
formatYesNoLabel,
|
||||
syncLeaveDuration,
|
||||
getLeaveFormPayload,
|
||||
getLeaveConfirmationPayload,
|
||||
getLeaveResultPayload,
|
||||
getLeaveAgentDisplayValue,
|
||||
submitLeaveForm: formApi.submitLeaveForm,
|
||||
editLeaveConfirmation: formApi.editLeaveConfirmation,
|
||||
confirmLeaveSubmission: formApi.confirmLeaveSubmission,
|
||||
tryHandleLeaveSend: flowApi.tryHandleLeaveSend,
|
||||
handleLeaveMarkdownClick: flowApi.handleLeaveMarkdownClick,
|
||||
syncCurrentUserProfile,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
/**
|
||||
* features/chat/composables/useChatPage.ts
|
||||
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
|
||||
*/
|
||||
import { computed, markRaw, ref, watch } from 'vue';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { config } from '@/config';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { useIsMobile } from '@/shared/composables/useIsMobile';
|
||||
import { useTheme } from '@/shared/composables/useTheme';
|
||||
import { stripReasoningPrelude } from '../utils/chatText';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { useChat } from './useChat';
|
||||
import { useChatAgent } from './useChatAgent';
|
||||
import { useChatAttachments } from './useChatAttachments';
|
||||
import { useChatBrowserPanel } from './useChatBrowserPanel';
|
||||
import { useChatGuides } from './useChatGuides';
|
||||
import { useChatLeave } from './useChatLeave';
|
||||
import { useChatQueryPreview } from './useChatQueryPreview';
|
||||
import { useChatRouteSync } from './useChatRouteSync';
|
||||
import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
createChatPageLocalMessageApi,
|
||||
createChatPageMarkdownApi,
|
||||
createChatPageSendApi,
|
||||
createLeaveMessageHandlers,
|
||||
createShippingMappingHandlers,
|
||||
createShippingPickerRefHolder,
|
||||
useChatPageDialogs,
|
||||
useChatPageUser,
|
||||
useChatPageVoice,
|
||||
} from '../page';
|
||||
|
||||
export function useChatPage() {
|
||||
const { t, locale } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const msg = useMessage();
|
||||
const { isMobile } = useIsMobile();
|
||||
const { appliedTheme, toggleLightDark } = useTheme();
|
||||
const deps: ChatDeps = { t, locale, msg, router, route };
|
||||
const chatStore = useChatStore();
|
||||
const { sidebarCollapsed } = storeToRefs(chatStore);
|
||||
|
||||
const currentAgentId = computed(() => {
|
||||
const id = Number(route.params.agentId);
|
||||
return Number.isFinite(id) && id > 0 ? id : 0;
|
||||
});
|
||||
|
||||
const { currentUser, currentUserDisplayName, currentUserEmployeeId, onAuthLogout, handleLogout, goToAdmin } =
|
||||
useChatPageUser(router);
|
||||
|
||||
const chatScrollContainer = ref<HTMLElement | null>(null);
|
||||
/** markRaw:避免 reactive(page) 解包内部 Ref,供 template ref 回写 */
|
||||
const scrollContainerHolder = markRaw({ el: chatScrollContainer });
|
||||
const input = ref('');
|
||||
const isSidebarOpen = ref(false);
|
||||
const copiedIndex = ref<number | null>(null);
|
||||
|
||||
const {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
createNewChatView,
|
||||
loadConversationState,
|
||||
sendMessage,
|
||||
} = useChat();
|
||||
|
||||
const browser = useChatBrowserPanel({
|
||||
warn: (text) => msg.warning(text),
|
||||
invalidUrlMessage: t('chat.invalidBrowserUrl'),
|
||||
enterUrlMessage: t('chat.enterBrowserUrl'),
|
||||
});
|
||||
|
||||
const queryPreview = useChatQueryPreview({ currentAgentId });
|
||||
const scroll = useChatScroll({ container: chatScrollContainer, messages });
|
||||
scroll.setupThinkingScrollWatch(isThinking, conversationId);
|
||||
|
||||
const resetPeripheralState = () => {
|
||||
browser.close();
|
||||
queryPreview.close();
|
||||
};
|
||||
|
||||
const disposePeripherals = () => {
|
||||
browser.stopResize();
|
||||
scroll.dispose();
|
||||
};
|
||||
|
||||
const chatGuides = useChatGuides({ currentAgentId });
|
||||
const agent = useChatAgent({ deps, currentAgentId, chatGuides });
|
||||
const attachmentApi = useChatAttachments({
|
||||
deps,
|
||||
currentAgentId,
|
||||
currentAgent: agent.currentAgent,
|
||||
});
|
||||
|
||||
const sourceFiles = useChatSourceFiles({ agentId: currentAgentId, t, msg, isMobile });
|
||||
const {
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
getSourceLinks,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
shouldExpandSourceDetails,
|
||||
openPreview,
|
||||
parsePlmPreviewLink,
|
||||
} = sourceFiles;
|
||||
|
||||
watch(currentAgentId, (id) => {
|
||||
chatStore.setCurrentAgentId(id > 0 ? id : null);
|
||||
}, { immediate: true });
|
||||
|
||||
const dialogs = useChatPageDialogs(messages);
|
||||
const { openDeleteConfirmDialog } = dialogs;
|
||||
|
||||
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
let startNewChat: () => void;
|
||||
|
||||
const {
|
||||
history,
|
||||
loadHistory,
|
||||
clearHistory,
|
||||
displayHistory,
|
||||
activeHistoryKey,
|
||||
handleHistorySelect,
|
||||
refreshHistoryAfterSend,
|
||||
setupConversationIdHistoryWatch,
|
||||
clearAllHistory,
|
||||
deleteHistoryItem,
|
||||
} = useChatSessions({
|
||||
deps,
|
||||
currentAgentId,
|
||||
conversationId,
|
||||
activeRunId,
|
||||
runs,
|
||||
activateRun,
|
||||
loadConversation: (id, opts) => loadConversation(id, opts),
|
||||
isSidebarOpen,
|
||||
onConfirmDelete: openDeleteConfirmDialog,
|
||||
startNewChat: () => startNewChat(),
|
||||
});
|
||||
|
||||
setupConversationIdHistoryWatch();
|
||||
|
||||
const voice = useChatPageVoice({ input, isThinking, msg, t });
|
||||
|
||||
const leave = useChatLeave({
|
||||
deps,
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
});
|
||||
|
||||
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
|
||||
conversationId,
|
||||
currentAgentId,
|
||||
});
|
||||
|
||||
const presetQuestion = computed(() => {
|
||||
const q = route.query.preset;
|
||||
return typeof q === 'string' ? q : '';
|
||||
});
|
||||
|
||||
const shipping = useChatShipping({
|
||||
deps,
|
||||
currentAgent: agent.currentAgent,
|
||||
currentAgentId,
|
||||
messages,
|
||||
conversationId,
|
||||
isThinking,
|
||||
history,
|
||||
loadHistory,
|
||||
input,
|
||||
chatScrollContainer,
|
||||
attachments: attachmentApi.attachments,
|
||||
selectedKb: agent.selectedKb,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
presetQuestion,
|
||||
saveLocalMessageToBackend,
|
||||
newLocalMessageId,
|
||||
stripReasoningPrelude,
|
||||
sendMessage,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
loadConversation: (id, opts) => loadConversation(id, opts),
|
||||
createNewChatView,
|
||||
});
|
||||
|
||||
const conversationApi = createChatPageConversationApi({
|
||||
deps,
|
||||
route,
|
||||
router,
|
||||
currentAgentId,
|
||||
conversationId,
|
||||
activeRunId,
|
||||
messages,
|
||||
isThinking,
|
||||
loadConversationState,
|
||||
createNewChatView,
|
||||
onConversationIdChanging: shipping.onConversationIdChanging,
|
||||
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
|
||||
onConversationLoadFailed: shipping.onConversationLoadFailed,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
clearHistory,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
input,
|
||||
resetCurrentAgent: () => { agent.currentAgent.value = null; },
|
||||
copiedIndex,
|
||||
resetPeripheralState,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
});
|
||||
|
||||
({ loadConversation, startNewChat } = conversationApi);
|
||||
const { resetChatStateForAgentChange } = conversationApi;
|
||||
|
||||
const markdown = createChatPageMarkdownApi({
|
||||
messages,
|
||||
isThinking,
|
||||
prepareMarkdownDisplayText: shipping.prepareMarkdownDisplayText,
|
||||
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
|
||||
parsePlmPreviewLink,
|
||||
openPreview,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
getSourceLinks,
|
||||
shouldExpandSourceDetails,
|
||||
getSourceTitle,
|
||||
getSourceMeta,
|
||||
getSourceBrief,
|
||||
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
|
||||
canOpenQueryPreview: queryPreview.canOpen,
|
||||
getQueryPreviewSummary: queryPreview.getSummary,
|
||||
openQueryPreviewDialog: queryPreview.openDialog,
|
||||
shippingActionButtonClass: shipping.shippingActionButtonClass,
|
||||
onShippingActionClick: shipping.handleShippingActionClick,
|
||||
});
|
||||
|
||||
const sendApi = createChatPageSendApi({
|
||||
input,
|
||||
messages,
|
||||
isThinking,
|
||||
currentAgentId,
|
||||
selectedKb: agent.selectedKb,
|
||||
isUploadingAttachments: attachmentApi.isUploadingAttachments,
|
||||
attachmentPolicy: attachmentApi.attachmentPolicy,
|
||||
attachments: attachmentApi.attachments,
|
||||
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
|
||||
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
|
||||
clearAttachments: attachmentApi.clearAttachments,
|
||||
sendMessage,
|
||||
refreshHistoryAfterSend,
|
||||
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
|
||||
tryHandleLeaveSend: leave.tryHandleLeaveSend,
|
||||
tryHandleShippingSend: shipping.tryHandleShippingSend,
|
||||
msg,
|
||||
t,
|
||||
copiedIndex,
|
||||
});
|
||||
|
||||
shipping.shippingBindSend(() => sendApi.handleSend());
|
||||
|
||||
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
|
||||
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
|
||||
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
|
||||
|
||||
const showChatRating = ref(false);
|
||||
|
||||
const routeSync = useChatRouteSync({
|
||||
deps,
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput: voice.cancelVoiceInput,
|
||||
syncCurrentUserProfile: leave.syncCurrentUserProfile,
|
||||
loadAgent: agent.loadAgent,
|
||||
loadUserAgents: agent.loadUserAgents,
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery: shipping.resumeShippingTaskFromQuery,
|
||||
handleSend: sendApi.handleSend,
|
||||
createNewChatView,
|
||||
onAuthLogout,
|
||||
onViewportResize: () => browser.syncViewportWidth(),
|
||||
disposePeripherals,
|
||||
scheduleScrollToBottom: () => scroll.scheduleScrollToBottom(),
|
||||
onMountedExtra: () => {
|
||||
showChatRating.value = config.workspace?.showChatRating ?? true;
|
||||
},
|
||||
input,
|
||||
});
|
||||
|
||||
watch(locale, (newLang) => {
|
||||
localStorage.setItem('hxops_lang', String(newLang));
|
||||
});
|
||||
|
||||
const handleSidebarNewChat = () => {
|
||||
startNewChat();
|
||||
isSidebarOpen.value = false;
|
||||
};
|
||||
|
||||
return {
|
||||
t,
|
||||
msg,
|
||||
isMobile,
|
||||
appliedTheme,
|
||||
toggleLightDark,
|
||||
currentAgentId,
|
||||
currentUser,
|
||||
chatScrollContainer,
|
||||
scrollContainerHolder,
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
input,
|
||||
browser,
|
||||
queryPreview,
|
||||
browserPanelOpen: browser.open,
|
||||
browserDraftUrl: browser.draftUrl,
|
||||
browserCurrentUrl: browser.currentUrl,
|
||||
browserFrameKey: browser.frameKey,
|
||||
browserPanelStyle: browser.panelStyle,
|
||||
isBrowserResizing: browser.isResizing,
|
||||
showQueryPreviewDialog: queryPreview.show,
|
||||
queryPreviewLoading: queryPreview.loading,
|
||||
queryPreviewError: queryPreview.error,
|
||||
queryPreviewState: queryPreview.state,
|
||||
...agent,
|
||||
agentGuides: chatGuides.guides,
|
||||
showGuideModal: chatGuides.showModal,
|
||||
activeGuideId: chatGuides.activeGuideId,
|
||||
activeGuide: chatGuides.activeGuide,
|
||||
showGuideSidebar: chatGuides.showSidebar,
|
||||
openGuideModal: chatGuides.openModal,
|
||||
...attachmentApi,
|
||||
filePreviewVisible,
|
||||
previewFile,
|
||||
isSidebarOpen,
|
||||
sidebarCollapsed,
|
||||
toggleBrowserPanel: browser.toggle,
|
||||
copiedIndex,
|
||||
displayHistory,
|
||||
activeHistoryKey,
|
||||
handleHistorySelect,
|
||||
clearAllHistory,
|
||||
deleteHistoryItem,
|
||||
isVoiceRecording: voice.isVoiceRecording,
|
||||
isVoiceTranscribing: voice.isVoiceTranscribing,
|
||||
handleVoiceFeatureClick: voice.handleVoiceFeatureClick,
|
||||
...leave,
|
||||
leaveMessageHandlers,
|
||||
shippingMappingHandlers,
|
||||
shippingPickerRefHolder,
|
||||
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
|
||||
messageBubbleHandlers: markdown.messageBubbleHandlers,
|
||||
shouldRenderMessage: markdown.shouldRenderMessage,
|
||||
canSendMessage: sendApi.canSendMessage,
|
||||
handleSend: sendApi.handleSend,
|
||||
copyToClipboard: sendApi.copyToClipboard,
|
||||
regenerate: sendApi.regenerate,
|
||||
handleOpenFeedback: dialogs.handleOpenFeedback,
|
||||
activeFeedbackMessageIndex: dialogs.activeFeedbackMessageIndex,
|
||||
showGeneralFeedbackDialog: dialogs.showGeneralFeedbackDialog,
|
||||
currentGeneralFeedbackChatLogId: dialogs.currentGeneralFeedbackChatLogId,
|
||||
showDeleteConfirmDialog: dialogs.showDeleteConfirmDialog,
|
||||
deleteConfirmMessage: dialogs.deleteConfirmMessage,
|
||||
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm: dialogs.handleDeleteConfirm,
|
||||
showChatRating,
|
||||
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
|
||||
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
|
||||
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
|
||||
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
|
||||
handleSidebarNewChat,
|
||||
goToWorkspace: routeSync.goToWorkspace,
|
||||
switchToAgent: agent.switchToAgent,
|
||||
loadUserAgents: agent.loadUserAgents,
|
||||
handleLogout,
|
||||
goToAdmin,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* features/chat/composables/useChatQueryPreview.ts
|
||||
* Text2SQL 查询结果全量预览弹窗:分页加载与消息 payload 解析。
|
||||
*/
|
||||
import { ref, type ComputedRef } from 'vue';
|
||||
import { getChatQueryPreviewPage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
type QueryPreviewPayload = {
|
||||
kind: 'text2sql_result_preview';
|
||||
previewable?: boolean;
|
||||
total_count?: number;
|
||||
preview_row_count?: number;
|
||||
query?: string;
|
||||
};
|
||||
|
||||
export interface QueryPreviewState {
|
||||
chatLogId: number;
|
||||
title: string;
|
||||
query: string;
|
||||
columns: string[];
|
||||
rows: unknown[][];
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface UseChatQueryPreviewOptions {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
|
||||
const { currentAgentId } = options;
|
||||
|
||||
const show = ref(false);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const state = ref<QueryPreviewState>({
|
||||
chatLogId: 0,
|
||||
title: '',
|
||||
query: '',
|
||||
columns: [],
|
||||
rows: [],
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
total: 0,
|
||||
});
|
||||
|
||||
const getPayload = (msg: ChatMessage): QueryPreviewPayload | null => {
|
||||
const payload = msg?.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
if ((payload as QueryPreviewPayload).kind !== 'text2sql_result_preview') return null;
|
||||
return payload as QueryPreviewPayload;
|
||||
};
|
||||
|
||||
const canOpen = (msg: ChatMessage) => {
|
||||
const payload = getPayload(msg);
|
||||
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
|
||||
};
|
||||
|
||||
const getSummary = (msg: ChatMessage) => {
|
||||
const payload = getPayload(msg);
|
||||
const total = Number(payload?.total_count || 0);
|
||||
if (total > 0) return `查看全部预览(共 ${total} 条)`;
|
||||
return '查看全部预览';
|
||||
};
|
||||
|
||||
const totalPages = () =>
|
||||
Math.max(1, Math.ceil((state.value.total || 0) / (state.value.pageSize || 100)));
|
||||
|
||||
const close = () => {
|
||||
show.value = false;
|
||||
error.value = '';
|
||||
};
|
||||
|
||||
const loadPage = async (chatLogId: number, page = 1) => {
|
||||
if (!currentAgentId.value) {
|
||||
error.value = '当前 Agent 未就绪,请稍后重试';
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const result = await getChatQueryPreviewPage(currentAgentId.value, chatLogId, {
|
||||
page,
|
||||
page_size: state.value.pageSize,
|
||||
});
|
||||
state.value = {
|
||||
...state.value,
|
||||
chatLogId,
|
||||
title: String(result.query || state.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||
query: String(result.query || '').trim(),
|
||||
columns: Array.isArray(result.columns) ? result.columns : [],
|
||||
rows: Array.isArray(result.rows) ? result.rows : [],
|
||||
page: Number(result.page || page || 1),
|
||||
pageSize: Number(result.page_size || state.value.pageSize || 100),
|
||||
total: Number(result.total || 0),
|
||||
};
|
||||
} catch (err: unknown) {
|
||||
error.value = (err as { message?: string })?.message || '加载全量预览失败';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openDialog = async (msg: ChatMessage) => {
|
||||
const chatLogId = Number(msg?.chat_log_id || 0);
|
||||
if (!chatLogId) return;
|
||||
const payload = getPayload(msg);
|
||||
state.value = {
|
||||
...state.value,
|
||||
chatLogId,
|
||||
title: String(payload?.query || msg?.content || '查询结果全量预览').trim() || '查询结果全量预览',
|
||||
query: String(payload?.query || '').trim(),
|
||||
page: 1,
|
||||
total: Number(payload?.total_count || 0),
|
||||
};
|
||||
show.value = true;
|
||||
await loadPage(chatLogId, 1);
|
||||
};
|
||||
|
||||
const changePage = async (delta: number) => {
|
||||
const nextPage = state.value.page + delta;
|
||||
if (nextPage < 1 || nextPage > totalPages()) return;
|
||||
await loadPage(state.value.chatLogId, nextPage);
|
||||
};
|
||||
|
||||
return {
|
||||
show,
|
||||
loading,
|
||||
error,
|
||||
state,
|
||||
totalPages,
|
||||
getPayload,
|
||||
canOpen,
|
||||
getSummary,
|
||||
openDialog,
|
||||
close,
|
||||
changePage,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* features/chat/composables/useChatRouteSync.ts
|
||||
* 路由与 Agent 切换时的状态同步、挂载/卸载生命周期。
|
||||
*/
|
||||
import { onBeforeUnmount, onMounted, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
|
||||
import { registerOpenAgentId } from '@/shared/utils/agentTabs';
|
||||
import { workspacePathFromLegacyView } from '@/features/workspace/constants/routes';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
|
||||
export interface UseChatRouteSyncOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
presetQuestion: ComputedRef<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string | null>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
resetChatStateForAgentChange: () => void;
|
||||
cancelVoiceInput: () => void;
|
||||
syncCurrentUserProfile: () => Promise<void>;
|
||||
loadAgent: () => Promise<void>;
|
||||
loadUserAgents: () => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
resumeShippingTaskFromQuery: () => Promise<void>;
|
||||
handleSend: (textOrEvent?: string | Event) => Promise<void>;
|
||||
createNewChatView: () => void;
|
||||
onAuthLogout: () => void;
|
||||
onViewportResize: () => void;
|
||||
disposePeripherals: () => void;
|
||||
scheduleScrollToBottom: () => void;
|
||||
onMountedExtra?: () => void | Promise<void>;
|
||||
input: Ref<string>;
|
||||
}
|
||||
|
||||
export function useChatRouteSync(options: UseChatRouteSyncOptions) {
|
||||
const {
|
||||
deps: { route, router },
|
||||
currentAgentId,
|
||||
presetQuestion,
|
||||
shippingTaskIdFromQuery,
|
||||
resetChatStateForAgentChange,
|
||||
cancelVoiceInput,
|
||||
syncCurrentUserProfile,
|
||||
loadAgent,
|
||||
loadUserAgents,
|
||||
loadHistory,
|
||||
loadConversation,
|
||||
resumeShippingTaskFromQuery,
|
||||
handleSend,
|
||||
createNewChatView,
|
||||
onAuthLogout,
|
||||
onViewportResize,
|
||||
disposePeripherals,
|
||||
scheduleScrollToBottom,
|
||||
onMountedExtra,
|
||||
input,
|
||||
} = options;
|
||||
|
||||
let routeSyncToken = 0;
|
||||
|
||||
const syncOpenAgentRegistration = () => {
|
||||
const id = Number(route.params.agentId);
|
||||
registerOpenAgentId(Number.isFinite(id) && id > 0 ? id : null);
|
||||
};
|
||||
|
||||
const onPageHide = () => {
|
||||
registerOpenAgentId(null);
|
||||
};
|
||||
|
||||
const goToWorkspace = (view?: string) => {
|
||||
setLastChatAgentId(currentAgentId.value);
|
||||
registerOpenAgentId(null);
|
||||
router.push({ path: workspacePathFromLegacyView(view), query: { no_redirect: '1' } });
|
||||
};
|
||||
|
||||
const syncChatStateForRoute = async () => {
|
||||
const agentId = currentAgentId.value;
|
||||
if (!agentId) return;
|
||||
|
||||
const syncToken = ++routeSyncToken;
|
||||
resetChatStateForAgentChange();
|
||||
cancelVoiceInput();
|
||||
setLastChatAgentId(agentId);
|
||||
syncOpenAgentRegistration();
|
||||
|
||||
await syncCurrentUserProfile();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadAgent();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadUserAgents();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
await loadHistory();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
|
||||
const convId = route.query.conversation_id as string;
|
||||
if (convId) {
|
||||
await loadConversation(convId, { force: true });
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
} else if (shippingTaskIdFromQuery.value) {
|
||||
await resumeShippingTaskFromQuery();
|
||||
if (syncToken !== routeSyncToken) return;
|
||||
}
|
||||
|
||||
if (presetQuestion.value) {
|
||||
input.value = presetQuestion.value;
|
||||
await handleSend();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('pagehide', onPageHide);
|
||||
window.addEventListener('hxops:logout', onAuthLogout);
|
||||
window.addEventListener('resize', onViewportResize);
|
||||
await syncChatStateForRoute();
|
||||
await onMountedExtra?.();
|
||||
scheduleScrollToBottom();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
|
||||
async ([nextAgentId, nextConversationId, nextPreset, nextTaskId], [prevAgentId, prevConversationId, prevPreset, prevTaskId]) => {
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextConversationId === prevConversationId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
nextAgentId === prevAgentId
|
||||
&& nextPreset === prevPreset
|
||||
&& nextTaskId === prevTaskId
|
||||
&& nextConversationId !== prevConversationId
|
||||
) {
|
||||
if (typeof nextConversationId === 'string' && nextConversationId) {
|
||||
await loadConversation(nextConversationId, { force: true });
|
||||
} else {
|
||||
createNewChatView();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
await syncChatStateForRoute();
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('pagehide', onPageHide);
|
||||
window.removeEventListener('hxops:logout', onAuthLogout);
|
||||
window.removeEventListener('resize', onViewportResize);
|
||||
disposePeripherals();
|
||||
});
|
||||
|
||||
return {
|
||||
goToWorkspace,
|
||||
syncChatStateForRoute,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* features/chat/composables/useChatScroll.ts
|
||||
* 聊天主区域滚动:贴底、滚到最新用户问题与思考态切换时的滚动策略。
|
||||
*/
|
||||
import { nextTick, watch, type Ref } from 'vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
export interface UseChatScrollOptions {
|
||||
container: Ref<HTMLElement | null>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
}
|
||||
|
||||
export function useChatScroll(options: UseChatScrollOptions) {
|
||||
const { container, messages } = options;
|
||||
let scrollToBottomFrame: number | null = null;
|
||||
|
||||
const scrollToBottom = async () => {
|
||||
await nextTick();
|
||||
const el = container.value;
|
||||
if (!el) return;
|
||||
el.scrollTo({
|
||||
top: el.scrollHeight,
|
||||
behavior: 'auto',
|
||||
});
|
||||
};
|
||||
|
||||
const scrollToUserQuestion = async () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
scrollToBottomFrame = null;
|
||||
}
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const el = container.value;
|
||||
if (!el) return;
|
||||
let lastUserIndex = -1;
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
if (messages.value[i]?.role === 'user') {
|
||||
lastUserIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastUserIndex < 0) return;
|
||||
const target = el.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
|
||||
target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
const scheduleScrollToBottom = () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
}
|
||||
scrollToBottomFrame = window.requestAnimationFrame(() => {
|
||||
scrollToBottomFrame = null;
|
||||
void scrollToBottom();
|
||||
});
|
||||
};
|
||||
|
||||
const dispose = () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
scrollToBottomFrame = null;
|
||||
}
|
||||
};
|
||||
|
||||
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
|
||||
const setupThinkingScrollWatch = (isThinking: Ref<boolean>, conversationId?: Ref<string | null>) => {
|
||||
let wasThinking = false;
|
||||
watch(
|
||||
() => ({
|
||||
messageCount: messages.value.length,
|
||||
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
|
||||
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
|
||||
isThinking: isThinking.value,
|
||||
conversationId: conversationId?.value || '',
|
||||
}),
|
||||
() => {
|
||||
if (wasThinking && !isThinking.value) {
|
||||
wasThinking = false;
|
||||
void scrollToUserQuestion();
|
||||
} else {
|
||||
if (isThinking.value) wasThinking = true;
|
||||
scheduleScrollToBottom();
|
||||
}
|
||||
},
|
||||
{ deep: false },
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
scrollToBottom,
|
||||
scrollToUserQuestion,
|
||||
scheduleScrollToBottom,
|
||||
setupThinkingScrollWatch,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* features/chat/composables/useChatSessions.ts
|
||||
* 单 Agent 侧栏会话历史:服务端列表加载、进行中 run 合并展示、选中/删除/清空。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
|
||||
import {
|
||||
deleteAllChatSessions,
|
||||
deleteChatSession,
|
||||
listChatSessions,
|
||||
} from '../api/chat.api';
|
||||
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
|
||||
export interface UseChatSessionsOptions {
|
||||
deps: ChatDeps;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
conversationId: Ref<string | null>;
|
||||
activeRunId: Ref<number | null>;
|
||||
runs: Ref<ChatRun[]>;
|
||||
activateRun: (runId: number) => void;
|
||||
/** 延迟绑定:ChatView 中 loadConversation 在 composable 初始化之后才赋值 */
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
isSidebarOpen: Ref<boolean>;
|
||||
/** 删除确认弹窗(由 ChatView 提供) */
|
||||
onConfirmDelete: (message: string, action: () => Promise<void> | void) => void;
|
||||
/** 新建对话:清空视图并同步路由 query */
|
||||
startNewChat: () => void;
|
||||
}
|
||||
|
||||
export function useChatSessions(options: UseChatSessionsOptions) {
|
||||
const {
|
||||
deps: { t, router, route },
|
||||
currentAgentId,
|
||||
conversationId,
|
||||
activeRunId,
|
||||
runs,
|
||||
activateRun,
|
||||
loadConversation,
|
||||
isSidebarOpen,
|
||||
onConfirmDelete,
|
||||
startNewChat,
|
||||
} = options;
|
||||
|
||||
const chatStore = useChatStore();
|
||||
|
||||
// ── 服务端会话列表 ────────────────────────────────────────
|
||||
const history = ref<ChatSessionItem[]>([]);
|
||||
|
||||
const hydrateHistoryFromStore = (agentId: number) => {
|
||||
const cached = chatStore.getSessionHistory(agentId);
|
||||
history.value = cached ? [...cached] : [];
|
||||
};
|
||||
|
||||
const loadHistory = async () => {
|
||||
const agentId = currentAgentId.value;
|
||||
if (!agentId) return;
|
||||
hydrateHistoryFromStore(agentId);
|
||||
try {
|
||||
const items = await listChatSessions(agentId);
|
||||
history.value = items;
|
||||
chatStore.setSessionHistory(agentId, items);
|
||||
} catch (e) {
|
||||
console.error('Failed to load history', e);
|
||||
}
|
||||
};
|
||||
|
||||
/** Agent 切换时先展示该 Agent 的缓存列表 */
|
||||
const clearHistory = () => {
|
||||
const agentId = currentAgentId.value;
|
||||
if (agentId) {
|
||||
hydrateHistoryFromStore(agentId);
|
||||
return;
|
||||
}
|
||||
history.value = [];
|
||||
};
|
||||
|
||||
// ── 展示列表:合并进行中 run 与服务端记录 ─────────────────
|
||||
const activeHistoryKey = computed(() => {
|
||||
if (conversationId.value) return conversationId.value;
|
||||
if (activeRunId.value) return `pending:${activeRunId.value}`;
|
||||
return '';
|
||||
});
|
||||
|
||||
const displayHistory = computed<DisplayHistoryItem[]>(() => {
|
||||
const server = history.value || [];
|
||||
const serverIds = new Set(server.map((h) => h.conversation_id));
|
||||
const pending: DisplayHistoryItem[] = (runs.value || [])
|
||||
.filter((r) => r.agentId === currentAgentId.value)
|
||||
.filter((r) => r.status === 'running')
|
||||
.filter((r) => r.runId !== activeRunId.value)
|
||||
.map((r) => ({
|
||||
id: 0,
|
||||
conversation_id: r.conversationId || `pending:${r.runId}`,
|
||||
title: (r.query || '').trim(),
|
||||
created_at: r.createdAt,
|
||||
__runId: r.runId,
|
||||
__status: r.status,
|
||||
}))
|
||||
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
|
||||
|
||||
const merged = [...pending, ...server] as DisplayHistoryItem[];
|
||||
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
|
||||
return merged;
|
||||
});
|
||||
|
||||
// ── 选中会话:优先恢复 run,否则拉取消息并同步路由 ───────
|
||||
const handleHistorySelect = async (item: DisplayHistoryItem) => {
|
||||
if (item.__runId) {
|
||||
activateRun(item.__runId);
|
||||
isSidebarOpen.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const run = runs.value.find(
|
||||
(r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id,
|
||||
);
|
||||
if (run && run.status === 'running') {
|
||||
activateRun(run.runId);
|
||||
isSidebarOpen.value = false;
|
||||
return;
|
||||
}
|
||||
|
||||
await loadConversation(item.conversation_id, { force: true });
|
||||
isSidebarOpen.value = false;
|
||||
|
||||
if (item.conversation_id.startsWith('pending:')) return;
|
||||
|
||||
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
|
||||
if (currentConvId === item.conversation_id) return;
|
||||
|
||||
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
|
||||
delete nextQuery.task_id;
|
||||
delete nextQuery.preset;
|
||||
await router.replace({ path: route.path, query: nextQuery });
|
||||
};
|
||||
|
||||
// ── 发送后 / 新会话 ID:按需刷新侧栏 ─────────────────────
|
||||
const refreshHistoryAfterSend = async () => {
|
||||
if (!conversationId.value && history.value.length === 0) {
|
||||
await loadHistory();
|
||||
return;
|
||||
}
|
||||
if (conversationId.value) {
|
||||
const exists = history.value.some((h) => h.conversation_id === conversationId.value);
|
||||
if (!exists) await loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const setupConversationIdHistoryWatch = () =>
|
||||
watch(
|
||||
() => conversationId.value,
|
||||
async (id, prev) => {
|
||||
if (!id || id === prev) return;
|
||||
const exists = history.value.some((item) => item.conversation_id === id);
|
||||
if (!exists) {
|
||||
await loadHistory();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// ── 删除单条 / 清空全部 ───────────────────────────────────
|
||||
const clearAllHistory = async () => {
|
||||
onConfirmDelete(t('chat.confirmClearHistory'), async () => {
|
||||
try {
|
||||
const agentId = currentAgentId.value;
|
||||
await deleteAllChatSessions(agentId);
|
||||
history.value = [];
|
||||
chatStore.setSessionHistory(agentId, []);
|
||||
runs.value = [];
|
||||
if (conversationId.value || activeRunId.value) {
|
||||
startNewChat();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to clear history', e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const deleteHistoryItem = async (id: string, event: Event) => {
|
||||
event.stopPropagation();
|
||||
onConfirmDelete(t('chat.confirmDeleteHistoryItem'), async () => {
|
||||
try {
|
||||
const agentId = currentAgentId.value;
|
||||
await deleteChatSession(id, agentId);
|
||||
history.value = history.value.filter((h) => h.conversation_id !== id);
|
||||
chatStore.patchSessionHistory(agentId, history.value);
|
||||
runs.value = runs.value.filter(
|
||||
(r) => !(r.agentId === currentAgentId.value && r.conversationId === id),
|
||||
);
|
||||
if (conversationId.value === id) {
|
||||
startNewChat();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete history item', e);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
history,
|
||||
loadHistory,
|
||||
clearHistory,
|
||||
displayHistory,
|
||||
activeHistoryKey,
|
||||
handleHistorySelect,
|
||||
refreshHistoryAfterSend,
|
||||
setupConversationIdHistoryWatch,
|
||||
clearAllHistory,
|
||||
deleteHistoryItem,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/composables/useChatSourceFiles.ts
|
||||
* 检索来源 / 源文件链接解析与预览。
|
||||
*/
|
||||
@@ -6,7 +6,7 @@ import { ref, type ComputedRef, type Ref } from 'vue';
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
import { resolveChatSourceFile } from '../api/chat.api';
|
||||
import type { SourceFileLink } from '../types/chat.types';
|
||||
import type { useMessage } from '@/composables/useMessage';
|
||||
import type { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
const PREFERRED_SOURCE_EXTS = new Set([
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* features/chat/constants/leave.ts
|
||||
* 请假功能常量:启用 Agent、假别编码、OA 跳转地址。
|
||||
*/
|
||||
|
||||
/** 支持本地请假表单的 Agent 名称白名单 */
|
||||
export const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
|
||||
|
||||
/** OA 系统基础地址(自动登录表单提交目标) */
|
||||
export const OA_BASE_URL = 'http://192.168.100.221:8888';
|
||||
export const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
|
||||
export const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
|
||||
export const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid=';
|
||||
export const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
|
||||
export const OA_PASSWORD_STORAGE_KEY = 'hxops_oa_login_password';
|
||||
|
||||
/** 下拉假别选项(value 为 OA 编码) */
|
||||
export const LEAVE_TYPES = [
|
||||
{ label: '事假(小时)', value: '005' },
|
||||
{ label: '病假(小时)', value: '006' },
|
||||
{ label: '丧假(天)', value: '007' },
|
||||
{ label: '年假(天)', value: '010' },
|
||||
{ label: '因公出差(小时)', value: '021' },
|
||||
{ label: '调休假(小时)', value: '025' },
|
||||
{ label: '产假(天)', value: '401' },
|
||||
{ label: '陪产假(天)', value: '402' },
|
||||
{ label: '婚假(天)', value: '403' },
|
||||
{ label: '住院病假(小时)', value: '405' },
|
||||
{ label: '工伤假(天)', value: '406' },
|
||||
{ label: '返乡假(小时)', value: 'ZZ01' },
|
||||
{ label: '事假(经理专用小时)', value: 'ZZ04' },
|
||||
{ label: '病假(经理专用小时)', value: 'ZZ05' },
|
||||
{ label: '丧假(经理专用天)', value: 'ZZ07' },
|
||||
{ label: '产假(经理专用天)', value: 'ZZ08' },
|
||||
{ label: '陪产假(经理专用天)', value: 'ZZ09' },
|
||||
{ label: '婚假(经理专用天)', value: 'ZZ10' },
|
||||
{ label: '其他假(小时)', value: '035' },
|
||||
{ label: '育儿假(小时)', value: '408' },
|
||||
] as const;
|
||||
|
||||
/** 按「天」计价的假别编码 */
|
||||
export const LEAVE_TYPE_BY_DAY = new Set(['010', '007', '401', '402', '403', '406', 'ZZ07', 'ZZ08', 'ZZ09', 'ZZ10']);
|
||||
|
||||
/** 自然语言关键词 → OA 假别编码 */
|
||||
export const LEAVE_TYPE_MAP: Record<string, string> = {
|
||||
事假: '005',
|
||||
病假: '006',
|
||||
丧假: '007',
|
||||
年假: '010',
|
||||
因公出差: '021',
|
||||
出差: '021',
|
||||
调休: '025',
|
||||
产假: '401',
|
||||
陪产假: '402',
|
||||
婚假: '403',
|
||||
住院: '405',
|
||||
工伤: '406',
|
||||
育儿假: '408',
|
||||
返乡: 'ZZ01',
|
||||
};
|
||||
|
||||
/** 发起前需校验余额的假别(年假、育儿假) */
|
||||
export const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* features/chat/constants/shipping.ts
|
||||
* 发货通知功能常量:任务编号正则、菜单动作规格与决策动作集合。
|
||||
*/
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
/** 工作区发货任务编号格式(如 SN-20250610-ABCDEF12) */
|
||||
export const SHIPPING_TASK_ID_RE = /SN-\d{8}-[A-F0-9]{8}/i;
|
||||
|
||||
export const SHIPPING_MENU_ACTION_SPECS: Record<
|
||||
ShippingMenuAction,
|
||||
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
|
||||
> = {
|
||||
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
|
||||
paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' },
|
||||
retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' },
|
||||
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
|
||||
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
|
||||
reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' },
|
||||
};
|
||||
|
||||
export const SHIPPING_DECISION_ACTIONS = new Set([
|
||||
'confirm',
|
||||
'confirm_inventory_mapping',
|
||||
'correct_inventory_mapping',
|
||||
'reparse_inventory',
|
||||
'reject',
|
||||
'reparse',
|
||||
'rematch',
|
||||
]);
|
||||
|
||||
/** 从文件名或 URL 提取扩展名(小写,不含点) */
|
||||
export const extractExt = (value: string) => {
|
||||
const text = (value || '').trim().toLowerCase();
|
||||
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
|
||||
const idx = withoutQuery.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return withoutQuery.slice(idx + 1).trim();
|
||||
};
|
||||
@@ -4,6 +4,30 @@
|
||||
*/
|
||||
export { useChat } from './composables/useChat';
|
||||
export { useChatHistory } from './composables/useChatHistory';
|
||||
export { useChatLeave } from './composables/useChatLeave';
|
||||
export { useChatShipping } from './composables/useChatShipping';
|
||||
export { useChatSessions } from './composables/useChatSessions';
|
||||
export { default as ChatSidebar } from './components/ChatSidebar.vue';
|
||||
export { default as ChatInputBar } from './components/ChatInputBar.vue';
|
||||
export { default as ChatWelcomePanel } from './components/ChatWelcomePanel.vue';
|
||||
export { default as ChatThinkingBubble } from './components/ChatThinkingBubble.vue';
|
||||
export { useChatSourceFiles } from './composables/useChatSourceFiles';
|
||||
export { useChatBrowserPanel } from './composables/useChatBrowserPanel';
|
||||
export { useChatQueryPreview } from './composables/useChatQueryPreview';
|
||||
export { useChatScroll } from './composables/useChatScroll';
|
||||
export { useChatPage } from './composables/useChatPage';
|
||||
export { useChatGuides } from './composables/useChatGuides';
|
||||
export { useChatAgent } from './composables/useChatAgent';
|
||||
export { useChatAttachments } from './composables/useChatAttachments';
|
||||
export { useChatRouteSync } from './composables/useChatRouteSync';
|
||||
export { useChatStore } from './stores/chat.store';
|
||||
export {
|
||||
CHAT_PAGE_KEY,
|
||||
useChatPageContext,
|
||||
type ChatPageContext,
|
||||
type ChatPageContextProvided,
|
||||
} from './composables/chat.context';
|
||||
export * from './api/chat.api';
|
||||
export * from './api/shipping.api';
|
||||
export type * from './types/chat.types';
|
||||
export type * from './types/shipping.api.types';
|
||||
@@ -0,0 +1,10 @@
|
||||
/** 请假(leave)子模块 barrel:纯函数 + handler 工厂 */
|
||||
export * from './leaveDateTime';
|
||||
export * from './leaveDisplay';
|
||||
export * from './leaveIntent';
|
||||
export * from './leavePayload';
|
||||
export * from './leaveLocalMessage';
|
||||
export * from './useChatLeaveOaLogin';
|
||||
export * from './useChatLeaveAgentPicker';
|
||||
export * from './useChatLeaveForm';
|
||||
export * from './useChatLeaveFlow';
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* 请假:日期时间解析、按天/按小时时长计算。
|
||||
*/
|
||||
import { LEAVE_TYPE_BY_DAY } from '../constants/leave';
|
||||
|
||||
export function formatDateTime(date: Date): string {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
const hours = String(date.getHours()).padStart(2, '0');
|
||||
const minutes = String(date.getMinutes()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}T${hours}:${minutes}`;
|
||||
}
|
||||
|
||||
export function parseDateTime(value: string): Date | null {
|
||||
const normalized = (value || '').trim().replace('T', ' ');
|
||||
const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
|
||||
if (!match) return null;
|
||||
const [, year, month, day, hour, minute] = match;
|
||||
const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
export function isLeaveTypeByDay(leaveType: string): boolean {
|
||||
return LEAVE_TYPE_BY_DAY.has(leaveType);
|
||||
}
|
||||
|
||||
export function calculateDurationHours(startTime: string, endTime: string): number {
|
||||
const start = parseDateTime(startTime);
|
||||
const end = parseDateTime(endTime);
|
||||
if (!start || !end || end.getTime() <= start.getTime()) return 0;
|
||||
return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2));
|
||||
}
|
||||
|
||||
export function syncLeaveDuration(form: { leaveType: string; startTime: string; endTime: string; durationHours: number }) {
|
||||
if (isLeaveTypeByDay(form.leaveType)) {
|
||||
const start = parseDateTime(form.startTime);
|
||||
const end = parseDateTime(form.endTime);
|
||||
if (!start || !end || end.getTime() <= start.getTime()) {
|
||||
form.durationHours = 0;
|
||||
return;
|
||||
}
|
||||
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
|
||||
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
|
||||
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
|
||||
form.durationHours = days * 8;
|
||||
} else {
|
||||
form.durationHours = calculateDurationHours(form.startTime, form.endTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 请假:假种标签、时长/是否展示、余额数字格式化。
|
||||
*/
|
||||
import { LEAVE_TYPES } from '../constants/leave';
|
||||
import { isLeaveTypeByDay } from './leaveDateTime';
|
||||
|
||||
export function getLeaveTypeLabel(val: string): string {
|
||||
const item = LEAVE_TYPES.find((x) => x.value === val);
|
||||
return item ? item.label : val;
|
||||
}
|
||||
|
||||
export function formatDurationLabel(
|
||||
hours: number,
|
||||
leaveType: string | undefined,
|
||||
t: (key: string) => string,
|
||||
): string {
|
||||
if (!hours) return `0 ${isLeaveTypeByDay(leaveType || '') ? t('chat.dayUnit') : t('chat.hourUnit')}`;
|
||||
if (isLeaveTypeByDay(leaveType || '')) {
|
||||
const days = Math.round(hours / 8);
|
||||
return `${days} ${t('chat.dayUnit')}`;
|
||||
}
|
||||
return `${hours} ${t('chat.hourUnit')}`;
|
||||
}
|
||||
|
||||
export function formatYesNoLabel(value: 0 | 1 | null): string {
|
||||
if (value === 0) return '是';
|
||||
if (value === 1) return '否';
|
||||
return '未选择';
|
||||
}
|
||||
|
||||
export function formatLeaveBalanceNumber(value: unknown, t: (key: string) => string): string {
|
||||
if (value === null || value === undefined) return t('chat.noData');
|
||||
const num = Number(value);
|
||||
if (Number.isNaN(num)) return String(value);
|
||||
return Number.isInteger(num) ? String(num) : num.toFixed(2);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* 请假:自然语言意图解析与强/弱意图区分。
|
||||
*/
|
||||
import { LEAVE_TYPE_MAP } from '../constants/leave';
|
||||
import type { ExtractedLeaveInfo } from '../types/leave.types';
|
||||
import { calculateDurationHours, isLeaveTypeByDay, parseDateTime } from './leaveDateTime';
|
||||
|
||||
export function extractLeaveTypeFromIntent(content: string): string {
|
||||
if (!content) return '';
|
||||
for (const [key, val] of Object.entries(LEAVE_TYPE_MAP)) {
|
||||
if (content.includes(key)) return val;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function extractLeaveInfoFromIntent(content: string): ExtractedLeaveInfo | null {
|
||||
const normalized = content.replace(/\s+/g, ' ').trim();
|
||||
let leaveType = extractLeaveTypeFromIntent(normalized);
|
||||
let startTime = '';
|
||||
let endTime = '';
|
||||
let durationHours = 0;
|
||||
|
||||
const today = new Date();
|
||||
const thisYear = today.getFullYear();
|
||||
|
||||
const parseDateStr = (m: RegExpMatchArray | null, groupOffset: number): Date | null => {
|
||||
if (!m) return null;
|
||||
const rawMo = m[groupOffset];
|
||||
const rawDa = m[groupOffset + 1];
|
||||
if (!rawMo || !rawDa) return null;
|
||||
const mo = parseInt(rawMo, 10);
|
||||
const da = parseInt(rawDa, 10);
|
||||
if (Number.isNaN(mo) || Number.isNaN(da) || mo < 1 || mo > 12 || da < 1 || da > 31) return null;
|
||||
return new Date(thisYear, mo - 1, da, 9, 0);
|
||||
};
|
||||
|
||||
const fmtDt = (d: Date, hour: number, minute: number) => {
|
||||
const y = d.getFullYear();
|
||||
const mo = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const da = String(d.getDate()).padStart(2, '0');
|
||||
const h = String(hour).padStart(2, '0');
|
||||
const mi = String(minute).padStart(2, '0');
|
||||
return `${y}-${mo}-${da}T${h}:${mi}`;
|
||||
};
|
||||
|
||||
let startDay: Date | null = null;
|
||||
let endDay: Date | null = null;
|
||||
const startHM = { h: 9, m: 0 };
|
||||
let endHM = { h: 18, m: 0 };
|
||||
|
||||
const rangeM = normalized.match(/从?(\d{1,2})[月./-](\d{1,2})[日号]?[到至—\-–](\d{1,2})[月./-]?(\d{1,2})[日号]?/);
|
||||
if (rangeM) {
|
||||
const s = parseDateStr(rangeM, 1);
|
||||
if (rangeM[3] && rangeM[3].length <= 2 && rangeM[4] && rangeM[4].length <= 2) {
|
||||
const eMo = parseInt(rangeM[3]!, 10);
|
||||
const eDa = parseInt(rangeM[4]!, 10);
|
||||
if (!Number.isNaN(eMo) && eMo >= 1 && eMo <= 12 && !Number.isNaN(eDa) && eDa >= 1 && eDa <= 31) {
|
||||
endDay = new Date(thisYear, eMo - 1, eDa, 18, 0);
|
||||
} else if (!Number.isNaN(eDa) && eDa >= 1 && eDa <= 31 && s) {
|
||||
endDay = new Date(thisYear, s.getMonth(), eDa, 18, 0);
|
||||
}
|
||||
}
|
||||
if (s) startDay = s;
|
||||
}
|
||||
|
||||
if (!startDay) {
|
||||
const singleM = normalized.match(/(\d{1,2})[月./-](\d{1,2})[日号]?/);
|
||||
if (singleM) {
|
||||
const s = parseDateStr(singleM, 1);
|
||||
if (s) {
|
||||
startDay = s;
|
||||
const dayUnitM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
|
||||
if (dayUnitM?.[1]) {
|
||||
const days = parseFloat(dayUnitM[1]);
|
||||
if (days > 1) endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate() + Math.ceil(days) - 1, 18, 0);
|
||||
else endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
|
||||
} else {
|
||||
endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hourM = normalized.match(/(\d+\.?\d*)\s*小时/);
|
||||
if (hourM?.[1]) {
|
||||
durationHours = parseFloat(hourM[1]);
|
||||
if (startDay && !endDay) {
|
||||
endDay = new Date(startDay.getTime() + durationHours * 3600000);
|
||||
}
|
||||
}
|
||||
|
||||
const dayM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
|
||||
if (dayM?.[1] && !hourM) {
|
||||
const days = parseFloat(dayM[1]);
|
||||
durationHours = days * 8;
|
||||
if (startDay && !endDay) {
|
||||
endDay = new Date(startDay.getFullYear(), startDay.getMonth(), startDay.getDate() + Math.ceil(days) - 1, 18, 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (startDay) {
|
||||
if (durationHours > 0 && durationHours <= 8 && !endDay) {
|
||||
endDay = new Date(startDay.getTime() + durationHours * 3600000);
|
||||
}
|
||||
startTime = fmtDt(startDay, startHM.h, startHM.m);
|
||||
}
|
||||
|
||||
if (endDay) {
|
||||
if (hourM && durationHours <= 8) {
|
||||
endHM = { h: 9 + Math.floor(durationHours), m: (durationHours % 1) * 60 };
|
||||
} else if (!hourM && durationHours > 0 && durationHours <= 8) {
|
||||
endHM = { h: 9 + Math.floor(durationHours), m: 0 };
|
||||
}
|
||||
endTime = fmtDt(endDay, endHM.h, endHM.m);
|
||||
}
|
||||
|
||||
if (startTime && endTime) {
|
||||
if (isLeaveTypeByDay(leaveType)) {
|
||||
const s = parseDateTime(startTime);
|
||||
const e = parseDateTime(endTime);
|
||||
if (s && e && e.getTime() > s.getTime()) {
|
||||
const sd = new Date(s.getFullYear(), s.getMonth(), s.getDate());
|
||||
const ed = new Date(e.getFullYear(), e.getMonth(), e.getDate());
|
||||
const days = Math.max(1, Math.round((ed.getTime() - sd.getTime()) / (24 * 3600 * 1000)) + 1);
|
||||
durationHours = days * 8;
|
||||
}
|
||||
} else {
|
||||
durationHours = durationHours || calculateDurationHours(startTime, endTime);
|
||||
}
|
||||
}
|
||||
|
||||
if (!leaveType && !startTime) return null;
|
||||
return { leaveType, startTime, endTime, durationHours };
|
||||
}
|
||||
|
||||
export function getLeaveIntentNormalized(content: string): string {
|
||||
return (content || '').replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
/** 区分「真请假」与「咨询流程/材料」类弱意图 */
|
||||
export function isStrongLeaveIntent(content: string): boolean {
|
||||
const normalized = getLeaveIntentNormalized(content);
|
||||
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
|
||||
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
|
||||
if (weakConsultationIntent.test(normalized)) return false;
|
||||
if (materialConsultationIntent.test(normalized)) return false;
|
||||
if (/^(请假|休假|年假|事假|病假|调休|休年假|请事假|请病假|请年假)$/.test(normalized)) return true;
|
||||
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请|帮我申请|我要申请|想申请|申请.*假|请.*假|休.*假)/.test(normalized);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 请假:本地消息 ID 生成与落库。
|
||||
*/
|
||||
import { saveLocalChatMessage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface LeaveLocalMessageContext {
|
||||
conversationId: Ref<string | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function createLeaveLocalMessageApi(ctx: LeaveLocalMessageContext) {
|
||||
let leaveFlowCounter = 0;
|
||||
|
||||
const newLocalMessageId = (prefix: string) => {
|
||||
leaveFlowCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${leaveFlowCounter}`;
|
||||
};
|
||||
|
||||
const saveLocalMessageToBackend = async (chatMsg: ChatMessage, userQuery = '') => {
|
||||
try {
|
||||
const data = await saveLocalChatMessage({
|
||||
conversation_id: ctx.conversationId.value,
|
||||
type: chatMsg.type,
|
||||
content: chatMsg.content,
|
||||
payload: chatMsg.payload,
|
||||
query: userQuery,
|
||||
agent_id: ctx.currentAgentId.value,
|
||||
});
|
||||
if (!ctx.conversationId.value && data.conversation_id) {
|
||||
ctx.conversationId.value = data.conversation_id;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
chatMsg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
}
|
||||
};
|
||||
|
||||
return { newLocalMessageId, saveLocalMessageToBackend };
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 请假:leave-form / leave-confirmation / leave-result payload 读取。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type {
|
||||
LeaveConfirmationPayload,
|
||||
LeaveFormPayload,
|
||||
LeaveRequestFormData,
|
||||
LeaveResultPayload,
|
||||
} from '../types/leave.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export function getLeaveFormPayload(chatMsg: ChatMessage): LeaveFormPayload | null {
|
||||
return chatMsg?.type === 'leave-form' && chatMsg?.payload ? chatMsg.payload as LeaveFormPayload : null;
|
||||
}
|
||||
|
||||
export function getLeaveConfirmationPayload(chatMsg: ChatMessage): LeaveConfirmationPayload | null {
|
||||
return chatMsg?.type === 'leave-confirmation' && chatMsg?.payload ? chatMsg.payload as LeaveConfirmationPayload : null;
|
||||
}
|
||||
|
||||
export function getLeaveResultPayload(chatMsg: ChatMessage): LeaveResultPayload | null {
|
||||
return chatMsg?.type === 'leave-result' && chatMsg?.payload ? chatMsg.payload as LeaveResultPayload : null;
|
||||
}
|
||||
|
||||
export function findMessageIndexByLocalId(messages: Ref<ChatMessage[]>, localId: string): number {
|
||||
return messages.value.findIndex((m) => m?.local_id === localId || (m?.payload as LeaveFormPayload | undefined)?.formId === localId);
|
||||
}
|
||||
|
||||
export function getLeaveAgentDisplayValue(form: LeaveRequestFormData): string {
|
||||
if (!form.agentName) return '';
|
||||
const parts = [form.agentName];
|
||||
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
|
||||
return parts.join(' / ');
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* 请假:OA 员工(代理人/申请人)搜索选择弹窗。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { listOaEmployees } from '../api/chat.api';
|
||||
import {
|
||||
findMessageIndexByLocalId,
|
||||
getLeaveFormPayload,
|
||||
} from './leavePayload';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { LeaveAgentOption } from '../types/leave.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface LeaveAgentPickerContext {
|
||||
currentAgentId: ComputedRef<number>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
saveLocalMessageToBackend: (chatMsg: ChatMessage) => Promise<void>;
|
||||
}
|
||||
|
||||
export function createLeaveAgentPickerApi(ctx: LeaveAgentPickerContext) {
|
||||
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
|
||||
const leaveAgentLoading = ref(false);
|
||||
const leaveAgentKeyword = ref('');
|
||||
const leaveAgentPage = ref(1);
|
||||
const leaveAgentHasMore = ref(true);
|
||||
const showLeaveAgentDialog = ref(false);
|
||||
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
|
||||
const activeLeaveAgentFormId = ref<string | null>(null);
|
||||
|
||||
const fetchLeaveAgents = async (isLoadMore = false) => {
|
||||
if (leaveAgentLoading.value) return;
|
||||
if (!isLoadMore) {
|
||||
leaveAgentPage.value = 1;
|
||||
leaveAgentOptions.value = [];
|
||||
}
|
||||
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const data = await listOaEmployees(ctx.currentAgentId.value, {
|
||||
keyword: leaveAgentKeyword.value,
|
||||
page: leaveAgentPage.value,
|
||||
page_size: 20,
|
||||
});
|
||||
if (isLoadMore) {
|
||||
leaveAgentOptions.value.push(...data.items);
|
||||
} else {
|
||||
leaveAgentOptions.value = data.items;
|
||||
}
|
||||
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
|
||||
} catch (e) {
|
||||
console.error('Failed to load OA employees', e);
|
||||
} finally {
|
||||
leaveAgentLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleAgentSearch = () => {
|
||||
void fetchLeaveAgents(false);
|
||||
};
|
||||
|
||||
const loadMoreAgents = () => {
|
||||
if (!leaveAgentHasMore.value) return;
|
||||
leaveAgentPage.value += 1;
|
||||
void fetchLeaveAgents(true);
|
||||
};
|
||||
|
||||
const loadAllAgents = async () => {
|
||||
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const data = await listOaEmployees(ctx.currentAgentId.value, {
|
||||
keyword: leaveAgentKeyword.value,
|
||||
page: 1,
|
||||
page_size: 100000,
|
||||
});
|
||||
leaveAgentOptions.value = data.items;
|
||||
leaveAgentHasMore.value = false;
|
||||
} catch (e) {
|
||||
console.error('Failed to load all OA employees', e);
|
||||
} finally {
|
||||
leaveAgentLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const openLeaveAgentDialog = (chatMsg: ChatMessage, role: 'agent' | 'applicant' = 'agent') => {
|
||||
const payload = getLeaveFormPayload(chatMsg);
|
||||
if (!payload || payload.submitting || payload.confirmationGenerated) return;
|
||||
activeLeaveAgentFormId.value = payload.formId;
|
||||
leaveUserSelectRole.value = role;
|
||||
showLeaveAgentDialog.value = true;
|
||||
leaveAgentKeyword.value = '';
|
||||
void fetchLeaveAgents(false);
|
||||
};
|
||||
|
||||
const closeLeaveAgentDialog = () => {
|
||||
showLeaveAgentDialog.value = false;
|
||||
activeLeaveAgentFormId.value = null;
|
||||
};
|
||||
|
||||
const selectLeaveAgent = (option: LeaveAgentOption) => {
|
||||
if (!activeLeaveAgentFormId.value) return;
|
||||
const sourceIndex = findMessageIndexByLocalId(ctx.messages, activeLeaveAgentFormId.value);
|
||||
if (sourceIndex < 0) {
|
||||
closeLeaveAgentDialog();
|
||||
return;
|
||||
}
|
||||
const sourceMsg = ctx.messages.value[sourceIndex];
|
||||
if (!sourceMsg) {
|
||||
closeLeaveAgentDialog();
|
||||
return;
|
||||
}
|
||||
const payload = getLeaveFormPayload(sourceMsg);
|
||||
if (!payload) {
|
||||
closeLeaveAgentDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
if (leaveUserSelectRole.value === 'agent') {
|
||||
payload.form.agentUid = option.uid;
|
||||
payload.form.agentEmployeeId = option.employeeId;
|
||||
payload.form.agentName = option.name;
|
||||
payload.form.agentJobTitle = option.jobtitle;
|
||||
payload.form.agentJobTitleName = option.jobtitleName;
|
||||
payload.form.agentDepartmentId = option.departmentid;
|
||||
payload.form.agentSubCompanyId1 = option.subcompanyid1;
|
||||
payload.form.agentDepartmentName = option.departmentName;
|
||||
payload.form.agentSubCompanyName = option.subcompanyName;
|
||||
} else {
|
||||
payload.form.applicantUid = option.uid;
|
||||
payload.form.employeeId = option.employeeId;
|
||||
payload.form.applicantName = option.name;
|
||||
payload.form.applicantJobTitle = option.jobtitle;
|
||||
payload.form.applicantJobTitleName = option.jobtitleName;
|
||||
payload.form.applicantDepartmentId = option.departmentid;
|
||||
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
|
||||
payload.form.applicantDepartmentName = option.departmentName;
|
||||
payload.form.applicantSubCompanyName = option.subcompanyName;
|
||||
}
|
||||
|
||||
closeLeaveAgentDialog();
|
||||
void ctx.saveLocalMessageToBackend(sourceMsg);
|
||||
};
|
||||
|
||||
return {
|
||||
leaveAgentOptions,
|
||||
leaveAgentLoading,
|
||||
leaveAgentKeyword,
|
||||
leaveAgentPage,
|
||||
leaveAgentHasMore,
|
||||
showLeaveAgentDialog,
|
||||
leaveUserSelectRole,
|
||||
handleAgentSearch,
|
||||
loadMoreAgents,
|
||||
loadAllAgents,
|
||||
openLeaveAgentDialog,
|
||||
closeLeaveAgentDialog,
|
||||
selectLeaveAgent,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 请假:强意图拦截、插入 leave-form 消息、Markdown 链接触发。
|
||||
*/
|
||||
import { listOaEmployees } from '../api/chat.api';
|
||||
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
|
||||
import { isStrongLeaveIntent, extractLeaveInfoFromIntent, extractLeaveTypeFromIntent } from './leaveIntent';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ExtractedLeaveInfo, LeaveFormPayload, LeaveRequestFormData } from '../types/leave.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface LeaveFlowContext {
|
||||
canUseLeaveFeature: ComputedRef<boolean>;
|
||||
isThinking: Ref<boolean>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
loadHistory: () => Promise<void>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
createLeaveFormData: (content?: string, extractedInfo?: ExtractedLeaveInfo | null) => LeaveRequestFormData;
|
||||
checkLeaveBalance: (leaveTypeCode: string) => Promise<{
|
||||
has_balance?: boolean;
|
||||
leave_type_label?: string;
|
||||
year?: string | number;
|
||||
total_hours?: unknown;
|
||||
used_hours?: unknown;
|
||||
remaining_hours?: unknown;
|
||||
} | null>;
|
||||
formatLeaveBalanceNumber: (value: unknown) => string;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
export function createLeaveFlowApi(ctx: LeaveFlowContext) {
|
||||
const ensureHistoryListed = async () => {
|
||||
if (ctx.history.value.length === 0 || !ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value)) {
|
||||
await ctx.loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const startLocalLeaveFlow = async (content: string) => {
|
||||
const extractedInfo = extractLeaveInfoFromIntent(content);
|
||||
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content);
|
||||
|
||||
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
|
||||
ctx.messages.value.push({ role: 'user', content, type: 'text' });
|
||||
|
||||
const thinkingMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: ctx.t('chat.queryLeaveBalance'),
|
||||
};
|
||||
ctx.messages.value.push(thinkingMsg);
|
||||
|
||||
const balance = await ctx.checkLeaveBalance(initialLeaveType);
|
||||
const thinkingIndex = ctx.messages.value.indexOf(thinkingMsg);
|
||||
if (thinkingIndex >= 0) {
|
||||
ctx.messages.value.splice(thinkingIndex, 1);
|
||||
}
|
||||
|
||||
if (balance && !balance.has_balance) {
|
||||
const unit = initialLeaveType === '010' ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
|
||||
const detailLines = [
|
||||
ctx.t('chat.leaveBalanceInsufficient', { label: balance.leave_type_label }),
|
||||
'',
|
||||
`| ${ctx.t('chat.leaveBalanceTableLeaveType')} | ${ctx.t('chat.leaveBalanceTableYear')} | ${ctx.t('chat.leaveBalanceTableAvailable')} | ${ctx.t('chat.leaveBalanceTableUsed')} | ${ctx.t('chat.leaveBalanceTableRemaining')} |`,
|
||||
'| :---: | :---: | :---: | :---: | :---: |',
|
||||
`| ${balance.leave_type_label} | ${balance.year} | ${ctx.formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
|
||||
'',
|
||||
ctx.t('chat.leaveBalanceContactHr'),
|
||||
];
|
||||
const noBalanceMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: detailLines.join('\n'),
|
||||
};
|
||||
ctx.messages.value.push(noBalanceMsg);
|
||||
await ctx.saveLocalMessageToBackend(noBalanceMsg, content);
|
||||
await ensureHistoryListed();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const formId = ctx.newLocalMessageId('leave-form');
|
||||
const payload: LeaveFormPayload = {
|
||||
formId,
|
||||
form: ctx.createLeaveFormData(content, extractedInfo),
|
||||
submitting: false,
|
||||
confirmationGenerated: false,
|
||||
};
|
||||
|
||||
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
|
||||
ctx.messages.value.push({ role: 'user', content, type: 'text' });
|
||||
}
|
||||
|
||||
const formMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'leave-form',
|
||||
content: ctx.t('chat.leaveFormIntro'),
|
||||
payload,
|
||||
local_id: formId,
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(formMsg);
|
||||
|
||||
try {
|
||||
const keyword = payload.form.applicantName || payload.form.employeeId;
|
||||
if (keyword) {
|
||||
const data = await listOaEmployees(ctx.currentAgentId.value, { keyword, page: 1, page_size: 1 });
|
||||
const match = (data.items || []).find((item) => item.employeeId === payload.form.employeeId);
|
||||
if (match) {
|
||||
payload.form.fillerJobTitle = match.jobtitle || '';
|
||||
payload.form.fillerJobTitleName = match.jobtitleName || '';
|
||||
payload.form.fillerDepartmentId = match.departmentid || '';
|
||||
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
|
||||
payload.form.fillerDepartmentName = match.departmentName || '';
|
||||
payload.form.fillerSubCompanyName = match.subcompanyName || '';
|
||||
payload.form.applicantUid = match.uid || '';
|
||||
payload.form.applicantJobTitle = match.jobtitle || '';
|
||||
payload.form.applicantJobTitleName = match.jobtitleName || '';
|
||||
payload.form.applicantDepartmentId = match.departmentid || '';
|
||||
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
|
||||
payload.form.applicantDepartmentName = match.departmentName || '';
|
||||
payload.form.applicantSubCompanyName = match.subcompanyName || '';
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to prefill OA user info', e);
|
||||
}
|
||||
|
||||
await ctx.saveLocalMessageToBackend(formMsg, content);
|
||||
await ensureHistoryListed();
|
||||
};
|
||||
|
||||
const tryHandleLeaveSend = (content: string) => {
|
||||
if (!ctx.canUseLeaveFeature.value || !isStrongLeaveIntent(content)) return false;
|
||||
void startLocalLeaveFlow(content);
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleLeaveMarkdownClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
|
||||
if (!actionElement) return false;
|
||||
const action = actionElement.getAttribute('data-leave-action');
|
||||
if (action !== 'start-leave-flow' || ctx.isThinking.value) return false;
|
||||
event.preventDefault();
|
||||
if (!ctx.canUseLeaveFeature.value) {
|
||||
ctx.msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
|
||||
return true;
|
||||
}
|
||||
void startLocalLeaveFlow('我要请假');
|
||||
return true;
|
||||
};
|
||||
|
||||
return { startLocalLeaveFlow, tryHandleLeaveSend, handleLeaveMarkdownClick };
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
/**
|
||||
* 请假:表单初始数据、校验、余额断言、确认与 OA 提交。
|
||||
*/
|
||||
import { getLeaveBalance, submitLeaveWorkflow } from '@/features/auth/api/user.api';
|
||||
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
|
||||
import { formatLeaveBalanceNumber, getLeaveTypeLabel } from './leaveDisplay';
|
||||
import {
|
||||
calculateDurationHours,
|
||||
formatDateTime,
|
||||
isLeaveTypeByDay,
|
||||
parseDateTime,
|
||||
syncLeaveDuration,
|
||||
} from './leaveDateTime';
|
||||
import { extractLeaveTypeFromIntent } from './leaveIntent';
|
||||
import {
|
||||
findMessageIndexByLocalId,
|
||||
getLeaveConfirmationPayload,
|
||||
getLeaveFormPayload,
|
||||
} from './leavePayload';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type {
|
||||
ExtractedLeaveInfo,
|
||||
LeaveConfirmationPayload,
|
||||
LeaveRequestFormData,
|
||||
} from '../types/leave.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface LeaveFormContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
currentUserDisplayName: ComputedRef<string>;
|
||||
currentUserEmployeeId: ComputedRef<string>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
msg: { warning: (text: string) => void; error: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
export function createLeaveFormApi(ctx: LeaveFormContext) {
|
||||
const createLeaveFormData = (content?: string, extractedInfo?: ExtractedLeaveInfo | null): LeaveRequestFormData => {
|
||||
const now = new Date();
|
||||
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || '');
|
||||
const isByDay = isLeaveTypeByDay(initialLeaveType);
|
||||
const sameDayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0);
|
||||
const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
|
||||
const defaultStart = formatDateTime(now);
|
||||
const defaultEnd = isByDay ? formatDateTime(sameDayEnd) : formatDateTime(oneHourLater);
|
||||
const startTime = extractedInfo?.startTime || defaultStart;
|
||||
const endTime = extractedInfo?.endTime || defaultEnd;
|
||||
let durationHours: number;
|
||||
if (isByDay) {
|
||||
const start = parseDateTime(startTime);
|
||||
const end = parseDateTime(endTime);
|
||||
if (start && end && end.getTime() > start.getTime()) {
|
||||
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
|
||||
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
|
||||
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
|
||||
durationHours = days * 8;
|
||||
} else {
|
||||
durationHours = 8;
|
||||
}
|
||||
} else if (extractedInfo?.durationHours) {
|
||||
durationHours = extractedInfo.durationHours;
|
||||
} else {
|
||||
durationHours = calculateDurationHours(startTime, endTime);
|
||||
}
|
||||
return {
|
||||
applicantName: ctx.currentUserDisplayName.value,
|
||||
employeeId: ctx.currentUserEmployeeId.value,
|
||||
applicantUid: '',
|
||||
applyTime: formatDateTime(now),
|
||||
fillerName: ctx.currentUserDisplayName.value,
|
||||
agentUid: '',
|
||||
agentEmployeeId: '',
|
||||
agentName: '',
|
||||
leaveType: initialLeaveType,
|
||||
startTime,
|
||||
endTime,
|
||||
durationHours,
|
||||
isOutOfOffice: 1,
|
||||
isWorkInjury: 1,
|
||||
};
|
||||
};
|
||||
|
||||
const checkLeaveBalance = async (leaveTypeCode: string) => {
|
||||
try {
|
||||
return await getLeaveBalance(leaveTypeCode);
|
||||
} catch (e) {
|
||||
console.error('Failed to check leave balance', e);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const validateLeaveForm = (form: LeaveRequestFormData) => {
|
||||
if (!form.applicantName.trim()) return ctx.t('chat.leaveApplicantRequired');
|
||||
if (!form.employeeId.trim()) return ctx.t('chat.employeeIdRequired');
|
||||
if (!form.leaveType.trim()) return ctx.t('chat.leaveTypeRequired');
|
||||
if (!form.agentUid.trim()) return ctx.t('chat.leaveAgentRequired');
|
||||
if (!parseDateTime(form.startTime)) return ctx.t('chat.startTimeRequired');
|
||||
if (!parseDateTime(form.endTime)) return ctx.t('chat.endTimeRequired');
|
||||
syncLeaveDuration(form);
|
||||
if (form.durationHours <= 0) return ctx.t('chat.durationInvalid');
|
||||
return '';
|
||||
};
|
||||
|
||||
const assertBalanceForForm = async (form: LeaveRequestFormData) => {
|
||||
if (!NEED_BALANCE_CHECK_TYPES.has(form.leaveType)) return true;
|
||||
const balance = await checkLeaveBalance(form.leaveType);
|
||||
if (!balance || balance.remaining_hours === null || balance.remaining_hours === undefined) return true;
|
||||
|
||||
const requestedHours = form.durationHours;
|
||||
if (requestedHours <= balance.remaining_hours) return true;
|
||||
|
||||
const isByDay = isLeaveTypeByDay(form.leaveType);
|
||||
const unit = isByDay ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
|
||||
const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours;
|
||||
const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours;
|
||||
const label = getLeaveTypeLabel(form.leaveType);
|
||||
ctx.msg.warning(ctx.t('chat.durationExceedsBalance', {
|
||||
label,
|
||||
requested: `${requestedDisplay}${unit}`,
|
||||
remaining: `${remainingDisplay}${unit}`,
|
||||
}));
|
||||
return false;
|
||||
};
|
||||
|
||||
const submitLeaveForm = async (chatMsg: ChatMessage) => {
|
||||
const payload = getLeaveFormPayload(chatMsg);
|
||||
if (!payload) return;
|
||||
syncLeaveDuration(payload.form);
|
||||
const error = validateLeaveForm(payload.form);
|
||||
if (error) {
|
||||
ctx.msg.warning(error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!(await assertBalanceForForm(payload.form))) return;
|
||||
|
||||
const existingConfirmIndex = ctx.messages.value.findIndex(
|
||||
(item) => item?.type === 'leave-confirmation' && (item?.payload as LeaveConfirmationPayload | undefined)?.formId === payload.formId,
|
||||
);
|
||||
if (existingConfirmIndex >= 0) {
|
||||
ctx.messages.value.splice(existingConfirmIndex, 1);
|
||||
}
|
||||
|
||||
payload.confirmationGenerated = true;
|
||||
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
|
||||
const confirmMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'leave-confirmation',
|
||||
content: ctx.t('chat.leaveConfirmPrompt'),
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
form: summary,
|
||||
submitting: false,
|
||||
},
|
||||
local_id: ctx.newLocalMessageId('leave-confirm'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(confirmMsg);
|
||||
|
||||
void ctx.saveLocalMessageToBackend(chatMsg);
|
||||
void ctx.saveLocalMessageToBackend(confirmMsg);
|
||||
};
|
||||
|
||||
const editLeaveConfirmation = (chatMsg: ChatMessage, index: number) => {
|
||||
const payload = getLeaveConfirmationPayload(chatMsg);
|
||||
if (!payload) return;
|
||||
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
|
||||
if (sourceIndex >= 0) {
|
||||
const sourceMsg = ctx.messages.value[sourceIndex];
|
||||
if (sourceMsg) {
|
||||
const sourcePayload = getLeaveFormPayload(sourceMsg);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.confirmationGenerated = false;
|
||||
void ctx.saveLocalMessageToBackend(sourceMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.messages.value.splice(index, 1);
|
||||
};
|
||||
|
||||
const confirmLeaveSubmission = async (chatMsg: ChatMessage) => {
|
||||
const payload = getLeaveConfirmationPayload(chatMsg);
|
||||
if (!payload || payload.submitting) return;
|
||||
|
||||
if (!(await assertBalanceForForm(payload.form))) return;
|
||||
|
||||
payload.submitting = true;
|
||||
|
||||
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
|
||||
let sourceMsg: ChatMessage | undefined;
|
||||
if (sourceIndex >= 0) {
|
||||
sourceMsg = ctx.messages.value[sourceIndex];
|
||||
if (sourceMsg) {
|
||||
const sourcePayload = getLeaveFormPayload(sourceMsg);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.submitting = true;
|
||||
sourcePayload.confirmationGenerated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await submitLeaveWorkflow(payload.form);
|
||||
const resultMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'leave-result',
|
||||
content: ctx.t('chat.leaveResultSubmitted'),
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
success: true,
|
||||
referenceNo: data.request_id || '-',
|
||||
submittedAt: data.submitted_at || formatDateTime(new Date()),
|
||||
requestName: data.request_name || '',
|
||||
},
|
||||
local_id: ctx.newLocalMessageId('leave-result'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(resultMsg);
|
||||
payload.confirmed = true;
|
||||
payload.submitting = false;
|
||||
void ctx.saveLocalMessageToBackend(chatMsg);
|
||||
void ctx.saveLocalMessageToBackend(resultMsg);
|
||||
} catch (error: unknown) {
|
||||
const errorMessage = error instanceof Error ? error.message : ctx.t('chat.oaLeaveSubmitFailed');
|
||||
ctx.msg.error(errorMessage);
|
||||
const resultMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'leave-result',
|
||||
content: ctx.t('chat.leaveSubmitFailedPrefix', { error: errorMessage }),
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
success: false,
|
||||
referenceNo: '-',
|
||||
submittedAt: formatDateTime(new Date()),
|
||||
errorMessage,
|
||||
},
|
||||
local_id: ctx.newLocalMessageId('leave-result'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(resultMsg);
|
||||
void ctx.saveLocalMessageToBackend(resultMsg);
|
||||
} finally {
|
||||
payload.submitting = false;
|
||||
if (sourceMsg) {
|
||||
const sourcePayload = getLeaveFormPayload(sourceMsg);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.submitting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
createLeaveFormData,
|
||||
checkLeaveBalance,
|
||||
submitLeaveForm,
|
||||
editLeaveConfirmation,
|
||||
confirmLeaveSubmission,
|
||||
formatLeaveBalanceNumber: (value: unknown) => formatLeaveBalanceNumber(value, ctx.t),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* 请假:OA 自动登录弹窗与 VerifyLogin 表单提交。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import {
|
||||
OA_AUTO_LOGIN_TARGET,
|
||||
OA_LEAVE_APPLY_PATH,
|
||||
OA_PASSWORD_STORAGE_KEY,
|
||||
OA_REQUEST_VIEW_PATH,
|
||||
OA_VERIFY_LOGIN_URL,
|
||||
} from '../constants/leave';
|
||||
import type { ComputedRef } from 'vue';
|
||||
|
||||
export interface LeaveOaLoginContext {
|
||||
currentUserEmployeeId: ComputedRef<string>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createLeaveOaLoginApi(ctx: LeaveOaLoginContext) {
|
||||
const showOALoginDialog = ref(false);
|
||||
const oaLoginEmployeeId = ref('');
|
||||
const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '');
|
||||
const oaLoginGopage = ref('');
|
||||
const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET);
|
||||
|
||||
const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => {
|
||||
const popup = window.open('about:blank', target);
|
||||
if (!popup) {
|
||||
ctx.msg.warning(ctx.t('chat.oaPopupBlocked'));
|
||||
return;
|
||||
}
|
||||
|
||||
const formHtml = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"><title>${ctx.t('chat.oaLoggingTitle')}</title></head>
|
||||
<body>
|
||||
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">${ctx.t('chat.oaLoggingBody')}</p>
|
||||
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
|
||||
<input type="hidden" name="loginid" value="${username}" />
|
||||
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '"')}" />
|
||||
<input type="hidden" name="gopage" value="${gopage}" />
|
||||
<input type="hidden" name="logintype" value="1" />
|
||||
</form>
|
||||
<script>document.getElementById('oaLoginForm').submit();<\/script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
popup.document.open();
|
||||
popup.document.write(formHtml);
|
||||
popup.document.close();
|
||||
};
|
||||
|
||||
const openOALeaveRequestDirectly = () => {
|
||||
const employeeId = ctx.currentUserEmployeeId.value;
|
||||
if (!employeeId || employeeId === '-') {
|
||||
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
|
||||
return;
|
||||
}
|
||||
oaLoginEmployeeId.value = employeeId;
|
||||
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
|
||||
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
|
||||
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
|
||||
showOALoginDialog.value = true;
|
||||
};
|
||||
|
||||
const confirmOALogin = () => {
|
||||
if (!oaLoginPassword.value.trim()) {
|
||||
ctx.msg.warning(ctx.t('chat.oaPasswordRequired'));
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
|
||||
showOALoginDialog.value = false;
|
||||
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
|
||||
};
|
||||
|
||||
const cancelOALogin = () => {
|
||||
showOALoginDialog.value = false;
|
||||
};
|
||||
|
||||
const openOARequestDirectly = (requestId: string) => {
|
||||
const normalizedRequestId = String(requestId || '').trim();
|
||||
if (!normalizedRequestId || normalizedRequestId === '-') {
|
||||
ctx.msg.warning(ctx.t('chat.oaRequestMissing'));
|
||||
return;
|
||||
}
|
||||
const employeeId = ctx.currentUserEmployeeId.value;
|
||||
if (!employeeId || employeeId === '-') {
|
||||
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
|
||||
return;
|
||||
}
|
||||
oaLoginEmployeeId.value = employeeId;
|
||||
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
|
||||
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
|
||||
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
|
||||
showOALoginDialog.value = true;
|
||||
};
|
||||
|
||||
return {
|
||||
showOALoginDialog,
|
||||
oaLoginEmployeeId,
|
||||
oaLoginPassword,
|
||||
confirmOALogin,
|
||||
cancelOALogin,
|
||||
openOALeaveRequestDirectly,
|
||||
openOARequestDirectly,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** 对话页编排子模块 barrel */
|
||||
export * from './useChatPageUser';
|
||||
export * from './useChatPageLocalMessage';
|
||||
export * from './useChatPageDialogs';
|
||||
export * from './useChatPageVoice';
|
||||
export * from './useChatPageMarkdown';
|
||||
export * from './useChatPageConversation';
|
||||
export * from './useChatPageSend';
|
||||
export * from './useChatPageHandlerBundles';
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* 对话页:加载历史会话、新建对话、切换 Agent 时重置状态。
|
||||
*/
|
||||
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ChatPageConversationContext {
|
||||
deps: { t: (key: string) => string; msg: { warning: (text: string) => void } };
|
||||
route: RouteLocationNormalizedLoaded;
|
||||
router: Router;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
conversationId: Ref<string | null>;
|
||||
activeRunId: Ref<number | null>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
isThinking: Ref<boolean>;
|
||||
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
|
||||
createNewChatView: () => void;
|
||||
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
|
||||
onConversationLoadedEmpty: () => Promise<void>;
|
||||
onConversationLoadFailed: () => Promise<void>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
clearHistory: () => void;
|
||||
clearAttachments: () => void;
|
||||
input: Ref<string>;
|
||||
resetCurrentAgent: () => void;
|
||||
copiedIndex: Ref<number | null>;
|
||||
resetPeripheralState: () => void;
|
||||
filePreviewVisible: Ref<boolean>;
|
||||
previewFile: Ref<unknown>;
|
||||
}
|
||||
|
||||
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
|
||||
const loadConversation = async (id: string, options?: { force?: boolean }) => {
|
||||
const force = options?.force ?? false;
|
||||
if (!force && ctx.conversationId.value === id && !ctx.activeRunId.value && ctx.messages.value.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const prevConversationId = ctx.conversationId.value;
|
||||
try {
|
||||
ctx.onConversationIdChanging(id, prevConversationId);
|
||||
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
|
||||
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
|
||||
if (!loaded?.length) {
|
||||
ctx.deps.msg.warning(ctx.deps.t('chat.historyEmpty'));
|
||||
await ctx.onConversationLoadedEmpty();
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load conversation', e);
|
||||
await ctx.onConversationLoadFailed();
|
||||
if (ctx.isShippingNoticeAgent.value && ctx.shippingTaskIdFromQuery.value && !ctx.isThinking.value) {
|
||||
return;
|
||||
}
|
||||
ctx.deps.msg.warning(ctx.deps.t('chat.historyLoadFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const startNewChat = () => {
|
||||
ctx.createNewChatView();
|
||||
void ctx.router.replace({ path: ctx.route.path, query: {} });
|
||||
};
|
||||
|
||||
const resetChatStateForAgentChange = () => {
|
||||
ctx.createNewChatView();
|
||||
ctx.clearHistory();
|
||||
ctx.clearAttachments();
|
||||
ctx.input.value = '';
|
||||
ctx.resetCurrentAgent();
|
||||
ctx.copiedIndex.value = null;
|
||||
ctx.resetPeripheralState();
|
||||
ctx.filePreviewVisible.value = false;
|
||||
ctx.previewFile.value = null;
|
||||
};
|
||||
|
||||
return { loadConversation, startNewChat, resetChatStateForAgentChange };
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 对话页:删除确认弹窗、消息反馈弹窗状态。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
|
||||
const showDeleteConfirmDialog = ref(false);
|
||||
const deleteConfirmMessage = ref('');
|
||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
||||
|
||||
const openDeleteConfirmDialog = (
|
||||
message: string,
|
||||
onConfirm: () => Promise<void> | void,
|
||||
) => {
|
||||
deleteConfirmMessage.value = message;
|
||||
pendingDeleteAction = onConfirm;
|
||||
showDeleteConfirmDialog.value = true;
|
||||
};
|
||||
|
||||
const closeDeleteConfirmDialog = () => {
|
||||
showDeleteConfirmDialog.value = false;
|
||||
deleteConfirmMessage.value = '';
|
||||
pendingDeleteAction = null;
|
||||
};
|
||||
|
||||
const handleDeleteConfirm = async () => {
|
||||
if (!pendingDeleteAction) return;
|
||||
await pendingDeleteAction();
|
||||
closeDeleteConfirmDialog();
|
||||
};
|
||||
|
||||
const showGeneralFeedbackDialog = ref(false);
|
||||
const activeFeedbackMessageIndex = ref<number | null>(null);
|
||||
|
||||
const handleOpenFeedback = (index: number) => {
|
||||
activeFeedbackMessageIndex.value = index;
|
||||
showGeneralFeedbackDialog.value = true;
|
||||
};
|
||||
|
||||
const currentGeneralFeedbackChatLogId = computed(() => {
|
||||
if (activeFeedbackMessageIndex.value !== null) {
|
||||
const msgItem = messages.value[activeFeedbackMessageIndex.value];
|
||||
const id = Number(msgItem?.chat_log_id);
|
||||
if (Number.isInteger(id) && id > 0) return id;
|
||||
}
|
||||
for (let i = messages.value.length - 1; i >= 0; i--) {
|
||||
const msgItem = messages.value[i];
|
||||
if (msgItem?.role === 'assistant') {
|
||||
const id = Number(msgItem?.chat_log_id);
|
||||
if (Number.isInteger(id) && id > 0) return id;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
return {
|
||||
showDeleteConfirmDialog,
|
||||
deleteConfirmMessage,
|
||||
openDeleteConfirmDialog,
|
||||
closeDeleteConfirmDialog,
|
||||
handleDeleteConfirm,
|
||||
showGeneralFeedbackDialog,
|
||||
activeFeedbackMessageIndex,
|
||||
handleOpenFeedback,
|
||||
currentGeneralFeedbackChatLogId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* 对话页:子组件 inject 用的 handlers 对象打包(请假表单、出货映射、消息气泡)。
|
||||
*/
|
||||
import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue';
|
||||
import type { ShippingMappingHandlers } from '../components/messages/ShippingInventoryMappingMessage.vue';
|
||||
import type { useChatLeave } from '../composables/useChatLeave';
|
||||
import type { useChatShipping } from '../composables/useChatShipping';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
type LeaveHandlerSource = Pick<
|
||||
ReturnType<typeof useChatLeave>,
|
||||
| 'getLeaveFormPayload'
|
||||
| 'getLeaveConfirmationPayload'
|
||||
| 'getLeaveResultPayload'
|
||||
| 'getLeaveAgentDisplayValue'
|
||||
| 'getLeaveTypeLabel'
|
||||
| 'formatDurationLabel'
|
||||
| 'formatYesNoLabel'
|
||||
| 'syncLeaveDuration'
|
||||
| 'openLeaveAgentDialog'
|
||||
| 'openOALeaveRequestDirectly'
|
||||
| 'openOARequestDirectly'
|
||||
| 'submitLeaveForm'
|
||||
| 'editLeaveConfirmation'
|
||||
| 'confirmLeaveSubmission'
|
||||
>;
|
||||
|
||||
type ShippingHandlerSource = Pick<
|
||||
ReturnType<typeof useChatShipping>,
|
||||
| 'getShippingInventoryMappingPayload'
|
||||
| 'normalizeShippingHeaderForDisplay'
|
||||
| 'hasShippingInventorySampleRows'
|
||||
| 'getShippingInventorySampleRowText'
|
||||
| 'reuploadShippingInventoryFromMappingForm'
|
||||
| 'applyShippingInventoryMappingForm'
|
||||
>;
|
||||
|
||||
/** 请假消息块 handlers(LeaveMessageBlock) */
|
||||
export function createLeaveMessageHandlers(leave: LeaveHandlerSource): LeaveMessageHandlers {
|
||||
return {
|
||||
getLeaveFormPayload: leave.getLeaveFormPayload,
|
||||
getLeaveConfirmationPayload: leave.getLeaveConfirmationPayload,
|
||||
getLeaveResultPayload: leave.getLeaveResultPayload,
|
||||
getLeaveAgentDisplayValue: leave.getLeaveAgentDisplayValue,
|
||||
getLeaveTypeLabel: leave.getLeaveTypeLabel,
|
||||
formatDurationLabel: leave.formatDurationLabel,
|
||||
formatYesNoLabel: leave.formatYesNoLabel,
|
||||
syncLeaveDuration: leave.syncLeaveDuration,
|
||||
openLeaveAgentDialog: leave.openLeaveAgentDialog,
|
||||
openOALeaveRequestDirectly: leave.openOALeaveRequestDirectly,
|
||||
openOARequestDirectly: leave.openOARequestDirectly,
|
||||
submitLeaveForm: leave.submitLeaveForm,
|
||||
editLeaveConfirmation: leave.editLeaveConfirmation,
|
||||
confirmLeaveSubmission: leave.confirmLeaveSubmission,
|
||||
};
|
||||
}
|
||||
|
||||
/** 出货库存映射块 handlers(ShippingInventoryMappingMessage) */
|
||||
export function createShippingMappingHandlers(shipping: ShippingHandlerSource): ShippingMappingHandlers {
|
||||
return {
|
||||
getPayload: shipping.getShippingInventoryMappingPayload,
|
||||
normalizeHeader: shipping.normalizeShippingHeaderForDisplay,
|
||||
hasSampleRows: shipping.hasShippingInventorySampleRows,
|
||||
getSampleRowText: shipping.getShippingInventorySampleRowText,
|
||||
reupload: shipping.reuploadShippingInventoryFromMappingForm,
|
||||
apply: shipping.applyShippingInventoryMappingForm,
|
||||
};
|
||||
}
|
||||
|
||||
/** 隐藏 file input ref 包裹,避免 template 自动解包 Ref */
|
||||
export function createShippingPickerRefHolder(pickerRef: Ref<HTMLInputElement | null>) {
|
||||
return { pickerRef };
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 对话页:本地消息落库(请假/出货等不经过 SSE 的消息)。
|
||||
*/
|
||||
import { saveLocalChatMessage } from '../api/chat.api';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ChatPageLocalMessageContext {
|
||||
conversationId: Ref<string | null>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
}
|
||||
|
||||
export function createChatPageLocalMessageApi(ctx: ChatPageLocalMessageContext) {
|
||||
let localMessageCounter = 0;
|
||||
|
||||
const newLocalMessageId = (prefix: string) => {
|
||||
localMessageCounter += 1;
|
||||
return `${prefix}-${Date.now()}-${localMessageCounter}`;
|
||||
};
|
||||
|
||||
const saveLocalMessageToBackend = async (localMsg: ChatMessage, userQuery: string = '') => {
|
||||
try {
|
||||
const data = await saveLocalChatMessage({
|
||||
conversation_id: ctx.conversationId.value,
|
||||
type: localMsg.type,
|
||||
content: localMsg.content,
|
||||
payload: localMsg.payload,
|
||||
query: userQuery,
|
||||
agent_id: ctx.currentAgentId.value,
|
||||
});
|
||||
if (!ctx.conversationId.value && data.conversation_id) {
|
||||
ctx.conversationId.value = data.conversation_id;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
localMsg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
}
|
||||
};
|
||||
|
||||
return { newLocalMessageId, saveLocalMessageToBackend };
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* 对话页:Markdown 渲染、消息可见性判断、PLM/请假链接点击。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { marked } from 'marked';
|
||||
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
|
||||
import type { ChatMessage, SourceFileLink } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
marked.setOptions({ gfm: true, breaks: true });
|
||||
|
||||
export interface ChatPageMarkdownContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
isThinking: Ref<boolean>;
|
||||
prepareMarkdownDisplayText: (text: string) => string;
|
||||
handleLeaveMarkdownClick: (event: MouseEvent) => void;
|
||||
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
|
||||
openPreview: (file: SourceFileLink) => Promise<void>;
|
||||
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
|
||||
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
|
||||
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
|
||||
shouldExpandSourceDetails: (msgItem: Record<string, unknown>) => boolean;
|
||||
getSourceTitle: ChatMessageBubbleHandlers['getSourceTitle'];
|
||||
getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta'];
|
||||
getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief'];
|
||||
getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload'];
|
||||
canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview'];
|
||||
getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary'];
|
||||
openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog'];
|
||||
shippingActionButtonClass: ChatMessageBubbleHandlers['shippingActionButtonClass'];
|
||||
onShippingActionClick: ChatMessageBubbleHandlers['onShippingActionClick'];
|
||||
}
|
||||
|
||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
if (msgItem?.type === 'leave-form' || msgItem?.type === 'leave-confirmation' || msgItem?.type === 'leave-result') return true;
|
||||
const content = (msgItem?.content || '').trim();
|
||||
if (content) return true;
|
||||
if (ctx.getMessageLinks(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
||||
if (ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>).length > 0) return true;
|
||||
return Array.isArray(msgItem?.attribution_parts) && msgItem.attribution_parts.length > 0;
|
||||
};
|
||||
|
||||
const shouldShowThinkingBubble = computed(() => {
|
||||
if (!ctx.isThinking.value) return false;
|
||||
let lastUserIndex = -1;
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i--) {
|
||||
if (ctx.messages.value[i]?.role === 'user') {
|
||||
lastUserIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (lastUserIndex < 0) return true;
|
||||
return !ctx.messages.value
|
||||
.slice(lastUserIndex + 1)
|
||||
.some((msgItem) => msgItem?.role === 'assistant' && shouldRenderMessage(msgItem));
|
||||
});
|
||||
|
||||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const anchor = target?.closest?.('a') as HTMLAnchorElement | null;
|
||||
const preview = ctx.parsePlmPreviewLink(anchor?.getAttribute('href') || '');
|
||||
if (preview) {
|
||||
event.preventDefault();
|
||||
void ctx.openPreview(preview);
|
||||
return;
|
||||
}
|
||||
ctx.handleLeaveMarkdownClick(event);
|
||||
};
|
||||
|
||||
const renderMarkdown = (text: string) => {
|
||||
if (!text) return '';
|
||||
const displayText = ctx.prepareMarkdownDisplayText(text);
|
||||
try {
|
||||
const rendered = marked.parse(displayText);
|
||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||
return html.replace(/<table\b[\s\S]*?<\/table>/gi, (tableHtml: string) => (
|
||||
`<div class="chat-table-scroll"><div class="chat-table-inner">${tableHtml}</div></div>`
|
||||
));
|
||||
} catch {
|
||||
return displayText;
|
||||
}
|
||||
};
|
||||
|
||||
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
|
||||
renderMarkdown,
|
||||
onMarkdownClick: handleChatMarkdownClick,
|
||||
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
||||
canOpenQueryPreview: ctx.canOpenQueryPreview,
|
||||
getQueryPreviewSummary: ctx.getQueryPreviewSummary,
|
||||
openQueryPreviewDialog: ctx.openQueryPreviewDialog,
|
||||
shippingActionButtonClass: ctx.shippingActionButtonClass,
|
||||
onShippingActionClick: ctx.onShippingActionClick,
|
||||
getDisplayRetrieverResources: (msgItem) => ctx.getDisplayRetrieverResources(msgItem as unknown as Record<string, unknown>),
|
||||
getSourceLinks: (resources) => ctx.getSourceLinks(resources),
|
||||
shouldExpandSourceDetails: (msgItem) => ctx.shouldExpandSourceDetails(msgItem as unknown as Record<string, unknown>),
|
||||
getSourceTitle: ctx.getSourceTitle,
|
||||
getSourceMeta: ctx.getSourceMeta,
|
||||
getSourceBrief: ctx.getSourceBrief,
|
||||
openPreview: ctx.openPreview,
|
||||
};
|
||||
|
||||
return {
|
||||
shouldRenderMessage,
|
||||
shouldShowThinkingBubble,
|
||||
messageBubbleHandlers,
|
||||
renderMarkdown,
|
||||
handleChatMarkdownClick,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 对话页:发送消息编排(出货/请假前置拦截 → Dify SSE)、复制与重新生成。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { copyTextToClipboard } from '@/shared/utils/clipboard';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ChatPageSendContext {
|
||||
input: Ref<string>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
isThinking: Ref<boolean>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
isUploadingAttachments: Ref<boolean>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
attachments: Ref<unknown[]>;
|
||||
allowsSendWithAttachmentsOnly: ComputedRef<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
clearAttachments: () => void;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
tryHandleShippingAttachmentAutoFlow: (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
tryHandleLeaveSend: (content: string) => boolean;
|
||||
tryHandleShippingSend: (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
trimmed: string,
|
||||
) => Promise<boolean>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
copiedIndex: Ref<number | null>;
|
||||
}
|
||||
|
||||
export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
const canSendMessage = computed(() => {
|
||||
if (ctx.isThinking.value || ctx.isUploadingAttachments.value) return false;
|
||||
if (ctx.input.value.trim()) return true;
|
||||
if (ctx.allowsSendWithAttachmentsOnly.value) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
const handleSend = async (textOrEvent?: string | Event) => {
|
||||
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || ctx.input.value;
|
||||
const trimmed = content.trim();
|
||||
if (await ctx.tryHandleShippingAttachmentAutoFlow(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
if (!trimmed || ctx.isThinking.value || ctx.isUploadingAttachments.value) return;
|
||||
if (ctx.tryHandleLeaveSend(content)) return;
|
||||
if (await ctx.tryHandleShippingSend(textOrEvent, content, trimmed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
|
||||
try {
|
||||
files = await ctx.buildFileSpecsForSend();
|
||||
} catch (e: unknown) {
|
||||
let suffix = '';
|
||||
if (e instanceof BusinessError) {
|
||||
const headers = e.details?.headers as Record<string, string> | undefined;
|
||||
const requestId = headers?.['x-request-id']
|
||||
|| headers?.['x-requestid']
|
||||
|| headers?.['request-id']
|
||||
|| headers?.['trace-id']
|
||||
|| headers?.['cf-ray'];
|
||||
if (requestId) suffix = `(rid=${requestId})`;
|
||||
}
|
||||
const message = e instanceof Error ? e.message : 'unknown error';
|
||||
ctx.msg.warning(`附件处理失败:${message}${suffix}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.clearAttachments();
|
||||
|
||||
await ctx.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
};
|
||||
|
||||
const copyToClipboard = async (message: { role?: string; content?: string }, index: number) => {
|
||||
const text = String(message?.content ?? '').trim();
|
||||
if (!text) {
|
||||
ctx.msg.warning(ctx.t('chat.actions.copyEmpty'));
|
||||
return;
|
||||
}
|
||||
const ok = await copyTextToClipboard(text);
|
||||
if (ok) {
|
||||
ctx.copiedIndex.value = index;
|
||||
setTimeout(() => {
|
||||
ctx.copiedIndex.value = null;
|
||||
}, 2000);
|
||||
return;
|
||||
}
|
||||
ctx.msg.warning(ctx.t('chat.actions.copyFailed'));
|
||||
};
|
||||
|
||||
const regenerate = () => {
|
||||
const lastUserMsg = [...ctx.messages.value].reverse().find((m) => m.role === 'user');
|
||||
if (lastUserMsg) {
|
||||
void handleSend(lastUserMsg.content);
|
||||
}
|
||||
};
|
||||
|
||||
return { canSendMessage, handleSend, copyToClipboard, regenerate };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 对话页:当前登录用户展示名、工号与登出/管理入口。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import type { Router } from 'vue-router';
|
||||
import { getStoredAuthUser, logoutAuth } from '@/shared/utils/auth';
|
||||
|
||||
export function useChatPageUser(router: Router) {
|
||||
const currentUser = ref(getStoredAuthUser());
|
||||
|
||||
const currentUserDisplayName = computed(() => {
|
||||
const realName = currentUser.value?.real_name?.trim();
|
||||
if (realName) return realName;
|
||||
const aliasName = (currentUser.value as { name?: string; wecom_name?: string } | null)?.name?.trim?.()
|
||||
|| (currentUser.value as { wecom_name?: string } | null)?.wecom_name?.trim?.();
|
||||
if (aliasName) return aliasName;
|
||||
const username = currentUser.value?.username?.trim();
|
||||
if (username && !/^\d+$/.test(username)) return username;
|
||||
return '当前用户';
|
||||
});
|
||||
|
||||
const currentUserEmployeeId = computed(() => {
|
||||
const employeeId = currentUser.value?.employee_id?.trim();
|
||||
if (employeeId) return employeeId;
|
||||
const username = currentUser.value?.username?.trim();
|
||||
return username || '-';
|
||||
});
|
||||
|
||||
const onAuthLogout = () => {
|
||||
currentUser.value = null;
|
||||
};
|
||||
|
||||
const handleLogout = () => {
|
||||
logoutAuth();
|
||||
onAuthLogout();
|
||||
router.push('/');
|
||||
};
|
||||
|
||||
const goToAdmin = () => {
|
||||
router.push('/admin');
|
||||
};
|
||||
|
||||
return {
|
||||
currentUser,
|
||||
currentUserDisplayName,
|
||||
currentUserEmployeeId,
|
||||
onAuthLogout,
|
||||
handleLogout,
|
||||
goToAdmin,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 对话页:语音输入(当前功能开关关闭,保留占位与思考态取消录音)。
|
||||
*/
|
||||
import { watch } from 'vue';
|
||||
import { getVoiceUnavailableErrorKey, useAudioTranscription } from '@/shared/composables/useAudioTranscription';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
const VOICE_INPUT_ENABLED = false;
|
||||
|
||||
export interface ChatPageVoiceContext {
|
||||
input: Ref<string>;
|
||||
isThinking: Ref<boolean>;
|
||||
msg: { info: (text: string) => void; warning: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function useChatPageVoice(ctx: ChatPageVoiceContext) {
|
||||
const {
|
||||
isRecording: isVoiceRecording,
|
||||
isTranscribing: isVoiceTranscribing,
|
||||
toggle: toggleVoiceInput,
|
||||
cancel: cancelVoiceInput,
|
||||
} = useAudioTranscription({
|
||||
onResult: (text) => {
|
||||
ctx.input.value = text;
|
||||
},
|
||||
onError: (key) => {
|
||||
ctx.msg.warning(ctx.t(key));
|
||||
},
|
||||
});
|
||||
|
||||
const handleVoiceFeatureClick = () => {
|
||||
if (!VOICE_INPUT_ENABLED) {
|
||||
ctx.msg.info(ctx.t('chat.devComingSoon'));
|
||||
return;
|
||||
}
|
||||
if (ctx.isThinking.value || isVoiceTranscribing.value) return;
|
||||
const unavailable = getVoiceUnavailableErrorKey();
|
||||
if (unavailable) {
|
||||
ctx.msg.warning(ctx.t(unavailable));
|
||||
return;
|
||||
}
|
||||
toggleVoiceInput(ctx.input.value);
|
||||
};
|
||||
|
||||
watch(ctx.isThinking, (thinking) => {
|
||||
if (thinking) cancelVoiceInput();
|
||||
});
|
||||
|
||||
return {
|
||||
isVoiceRecording,
|
||||
isVoiceTranscribing,
|
||||
handleVoiceFeatureClick,
|
||||
cancelVoiceInput,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/** 出货(shipping)子模块 barrel:纯函数 + handler 工厂 + 动作刷新 */
|
||||
export * from './shippingText';
|
||||
export * from './shippingMenu';
|
||||
export * from './shippingIntents';
|
||||
export * from './shippingMapping';
|
||||
export * from './shippingTaskId';
|
||||
export * from './shippingDownload';
|
||||
export * from './shippingDecisionFormat';
|
||||
export * from './shippingUploadPrompt';
|
||||
export * from './shippingLocalMessages';
|
||||
export * from './shippingConversation';
|
||||
export * from './useChatShippingRefresh';
|
||||
export * from './useChatShippingMappingForm';
|
||||
export * from './useChatShippingDecision';
|
||||
export * from './useChatShippingMenuHandler';
|
||||
export * from './useChatShippingUploadHandler';
|
||||
export * from './useChatShippingSendHandler';
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 出货聊天:会话侧栏同步、带任务编号的菜单消息发送。
|
||||
*/
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingConversationContext {
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
export async function ensureShippingHistorySynced(ctx: ShippingConversationContext) {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
await ctx.loadHistory();
|
||||
} else if (ctx.conversationId.value) {
|
||||
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
|
||||
if (!exists) await ctx.loadHistory();
|
||||
}
|
||||
}
|
||||
|
||||
export function createShippingConversationHelpers(ctx: ShippingConversationContext) {
|
||||
const sendShippingMenuMessage = async (message: string) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
const text = taskId ? `${message}\n任务编号:${taskId}` : message;
|
||||
await ctx.sendMessage(text, ctx.currentAgentId.value, ctx.selectedKb.value, []);
|
||||
await ensureShippingHistorySynced(ctx);
|
||||
};
|
||||
|
||||
return { sendShippingMenuMessage, ensureShippingHistorySynced };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 出货聊天:决策 API 响应 → 助手消息 Markdown 文案(纯函数)。
|
||||
*/
|
||||
export function formatShippingDecisionAssistantMessage(
|
||||
decision: string,
|
||||
result: { message?: string; data?: Record<string, unknown>; checkpoint?: string },
|
||||
taskId: string,
|
||||
fallbackDoneMessage: string,
|
||||
): string {
|
||||
const lines: string[] = [result.message || fallbackDoneMessage];
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = (result.data?.schema_preview || {}) as Record<string, unknown>;
|
||||
const headers = Array.isArray(preview.headers) ? (preview.headers as unknown[]).filter(Boolean) : [];
|
||||
const suggested = (preview.suggested_mapping || {}) as Record<string, string>;
|
||||
if (preview.header_row_index) {
|
||||
lines.push('', `表头在第 ${preview.header_row_index} 行:${headers.join(' | ')}`);
|
||||
} else if (headers.length) {
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.sku ? `- sku → ${suggested.sku}` : null,
|
||||
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
|
||||
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
|
||||
].filter((line): line is string => Boolean(line));
|
||||
if (mappingLines.length) {
|
||||
lines.push('', '建议列映射:', ...mappingLines);
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。',
|
||||
'也可点击「选择库存文件」重新上传。',
|
||||
);
|
||||
} else if (decision === 'confirm_inventory_mapping') {
|
||||
if (String(result.checkpoint || '').trim() === 'map_ok') {
|
||||
lines.push('', '下一步:匹配库存与发货需求(match_inventory)。');
|
||||
}
|
||||
} else if (decision === 'reparse_inventory') {
|
||||
lines.push('', '请重新上传或粘贴库存 Excel。');
|
||||
}
|
||||
lines.push('', `任务编号:${taskId}`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 出货聊天:发货 Excel 浏览器下载(触发 a[download])。
|
||||
*/
|
||||
import { workspaceShippingExportUrl } from '@/features/chat/api/shipping.api';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export async function downloadWorkspaceShippingExcelFile(taskId: string): Promise<void> {
|
||||
const url = workspaceShippingExportUrl(taskId);
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error((body as { error?: string; message?: string })?.error || (body as { message?: string })?.message || res.statusText);
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition');
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = objectUrl;
|
||||
const rawName = disposition?.match(/filename\*?=(?:UTF-8'')?["']?([^;"'\n]+)/)?.[1] || `${taskId}.xlsx`;
|
||||
try {
|
||||
a.download = decodeURIComponent(rawName);
|
||||
} catch {
|
||||
a.download = rawName;
|
||||
}
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* 出货聊天:用户输入意图识别(纯函数,供 handleSend 前置拦截)。
|
||||
*
|
||||
* 覆盖:手工上传声明、库存上传、生成/下载 Excel、自然语言列映射(sku→列名)。
|
||||
*/
|
||||
import { resolveShippingNumericChoice } from './shippingMenu';
|
||||
import type { ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
if (!raw) return null;
|
||||
if (!/[→>=-]/.test(raw)) return null;
|
||||
const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
||||
const mapping: Record<string, string> = {};
|
||||
const normalizeRight = (s: string) => String(s || '')
|
||||
.replace(/[::]/g, '')
|
||||
.replace(/列$/g, '')
|
||||
.replace(/字段$/g, '')
|
||||
.replace(/^\[|\]$/g, '')
|
||||
.trim();
|
||||
const toKey = (left: string) => {
|
||||
const s = left.toLowerCase();
|
||||
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
|
||||
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
|
||||
if (s.includes('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
|
||||
return '';
|
||||
};
|
||||
for (const line of lines) {
|
||||
const m = line.match(/^\s*(.+?)\s*(?:→|->|=>|=|:|:)\s*(.+?)\s*$/);
|
||||
if (!m) continue;
|
||||
const left = m[1];
|
||||
const right = m[2];
|
||||
if (!left || !right) continue;
|
||||
const key = toKey(left.trim());
|
||||
if (!key) continue;
|
||||
const col = normalizeRight(right);
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.sku || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
export function isShippingManualUploadIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/已在货代系统手工上传/,
|
||||
/已手工上传/,
|
||||
/手工上传完成/,
|
||||
/手动上传完成/,
|
||||
/货代.*上传完成/,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingInventoryUploadIntent(text: string, assistantContext: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
const choice = resolveShippingNumericChoice(normalized, assistantContext);
|
||||
if (choice === 'upload') return true;
|
||||
return [
|
||||
/^上传库存$/,
|
||||
/上传库存文件/,
|
||||
/手工上传/,
|
||||
/选择库存/,
|
||||
/upload.*inventory/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingGenerateExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/^生成发货excel$/i,
|
||||
/^生成发货\s*excel$/i,
|
||||
/生成发货.*excel/i,
|
||||
/生成.*发货.*excel/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export function isShippingDownloadExcelIntent(text: string): boolean {
|
||||
const normalized = text.trim();
|
||||
if (!normalized) return false;
|
||||
return [
|
||||
/^下载excel$/i,
|
||||
/^下载发货excel$/i,
|
||||
/下载.*excel/i,
|
||||
].some((pattern) => pattern.test(normalized));
|
||||
}
|
||||
|
||||
export type { ShippingMenuAction };
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* 出货聊天:本地消息写入(不经过 Dify SSE,直接 push 到 messages 并落库)。
|
||||
*/
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingLocalMessageContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function createShippingLocalMessages(ctx: ShippingLocalMessageContext) {
|
||||
const pushShippingLocalUserMessage = async (text: string) => {
|
||||
const content = String(text || '').trim();
|
||||
if (!content) return;
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, content);
|
||||
};
|
||||
|
||||
const pushShippingLocalAssistantMessage = async (text: string) => {
|
||||
const content = String(text || '').trim();
|
||||
if (!content) return;
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg);
|
||||
};
|
||||
|
||||
return { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage };
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* 出货聊天:库存列映射 payload 读取与字段对齐 Markdown 生成(纯函数)。
|
||||
*
|
||||
* 消息 type === 'shipping-inventory-mapping' 时 payload 含 schema_preview + form。
|
||||
*/
|
||||
import { normalizeShippingHeaderForDisplay } from './shippingText';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
|
||||
export function getShippingInventoryMappingPayload(chatMsg: ChatMessage): ShippingInventoryMappingFormPayload | null {
|
||||
if (!chatMsg || chatMsg.type !== 'shipping-inventory-mapping') return null;
|
||||
const payload = chatMsg.payload;
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const taskId = String((payload as ShippingInventoryMappingFormPayload).taskId || '').trim();
|
||||
const schemaPreview = (payload as ShippingInventoryMappingFormPayload).schema_preview;
|
||||
const form = (payload as ShippingInventoryMappingFormPayload).form;
|
||||
if (!taskId || !schemaPreview || !form) return null;
|
||||
return payload as ShippingInventoryMappingFormPayload;
|
||||
}
|
||||
|
||||
export function hasShippingInventorySampleRows(chatMsg: ChatMessage): boolean {
|
||||
const rows = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows;
|
||||
return Array.isArray(rows) && rows.length > 0;
|
||||
}
|
||||
|
||||
export function getShippingInventorySampleRowText(chatMsg: ChatMessage): string {
|
||||
const row = getShippingInventoryMappingPayload(chatMsg)?.schema_preview?.sample_rows?.[0];
|
||||
return Array.isArray(row) ? row.map((cell) => String(cell)).join(' | ') : '';
|
||||
}
|
||||
|
||||
export function buildShippingFieldAlignmentText(payload: { data?: { field_alignment?: Record<string, unknown> } }): string {
|
||||
const alignment = payload?.data?.field_alignment;
|
||||
if (!alignment || typeof alignment !== 'object') return '';
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
|
||||
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
|
||||
];
|
||||
const lines: string[] = [];
|
||||
const matchRule = String((alignment as { match_rule?: string }).match_rule || '').trim();
|
||||
if (matchRule) lines.push(`匹配规则:${matchRule}`);
|
||||
lines.push('', '字段对齐表:', '', '|系统字段|库存列|', '|---|---|');
|
||||
for (const [k, v] of rows) {
|
||||
lines.push(`|${k}|${v}|`);
|
||||
}
|
||||
const warnings = Array.isArray((alignment as { warnings?: unknown[] }).warnings)
|
||||
? (alignment as { warnings: unknown[] }).warnings.filter(Boolean)
|
||||
: [];
|
||||
if (warnings.length) {
|
||||
lines.push('', '提示:', ...warnings.map((w) => `- ${String(w)}`));
|
||||
}
|
||||
return lines.join('\n').trim();
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* 出货聊天:数字菜单解析、动作按钮合并、决策文本识别(纯函数)。
|
||||
*
|
||||
* 菜单行格式示例:「1. 上传库存文件」→ action: upload
|
||||
* resolveShippingActionButtons:优先 API 按钮,其次 HTML 指令,最后内容推断
|
||||
*/
|
||||
import { extractShippingActionsDirective } from './shippingText';
|
||||
import type { ShippingActionButton, ShippingMenuAction } from '../types/shipping.types';
|
||||
|
||||
export function shippingActionButtonClass(variant?: string): string {
|
||||
if (variant === 'primary') {
|
||||
return 'rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
if (variant === 'danger') {
|
||||
return 'rounded-xl border border-rose-200 bg-rose-50 px-4 py-2 text-sm font-medium text-rose-700 transition hover:bg-rose-100 disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
return 'rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60';
|
||||
}
|
||||
|
||||
export function normalizeMenuDigit(ch: string): number {
|
||||
const full = '0123456789';
|
||||
const idx = full.indexOf(ch);
|
||||
return idx >= 0 ? idx : Number(ch);
|
||||
}
|
||||
|
||||
export function classifyShippingMenuLine(desc: string): ShippingMenuAction | null {
|
||||
const normalized = String(desc || '').trim();
|
||||
if (!normalized) return null;
|
||||
if (/已确认/.test(normalized)) return null;
|
||||
if (/(?:选择|上传).*(?:库存|excel|xlsx|xls|csv)/i.test(normalized)) return 'upload';
|
||||
if (/粘贴|文本|小量|直接发/i.test(desc)) return 'paste';
|
||||
if (/(?:重试|重新)\s*RPA|重试.*(?:导出|获取|拉取)|RPA.*(?:导出|获取|拉取).*重试/i.test(desc)) return 'retry_rpa';
|
||||
if (/重新解析|重解析|reparse/i.test(desc)) return 'reparse';
|
||||
if (/驳回|取消|reject/i.test(desc)) return 'reject';
|
||||
if (/^(?:确认|confirm)\b/i.test(normalized)) return 'confirm';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function parseShippingMenuFromContext(
|
||||
ctx: string,
|
||||
): Map<number, { action: ShippingMenuAction; desc: string }> {
|
||||
const map = new Map<number, { action: ShippingMenuAction; desc: string }>();
|
||||
for (const line of String(ctx || '').split('\n')) {
|
||||
const m = line.match(/^\s*([1-91-9])[\.、\)::]?\s*(.+)$/);
|
||||
if (!m?.[1] || !m[2]) continue;
|
||||
const num = normalizeMenuDigit(m[1]);
|
||||
if (!Number.isFinite(num) || num < 1) continue;
|
||||
const desc = String(m[2] || '').trim();
|
||||
const action = classifyShippingMenuLine(desc);
|
||||
if (action) map.set(num, { action, desc });
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
export function resolveShippingNumericChoice(
|
||||
text: string,
|
||||
assistantContext: string,
|
||||
): ShippingMenuAction | null {
|
||||
const normalized = text.trim();
|
||||
if (!/^[1-91-9](?:[\.\、\)::]?)$/.test(normalized)) return null;
|
||||
const num = normalizeMenuDigit(normalized.charAt(0));
|
||||
return parseShippingMenuFromContext(assistantContext).get(num)?.action || null;
|
||||
}
|
||||
|
||||
export function normalizeApiShippingButtons(
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
): ShippingActionButton[] {
|
||||
return (apiButtons || []).map((button) => ({
|
||||
...button,
|
||||
variant: (button.variant === 'primary' || button.variant === 'secondary' || button.variant === 'danger')
|
||||
? button.variant
|
||||
: undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveShippingActionButtons(
|
||||
content: string,
|
||||
apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null,
|
||||
opts?: { apiResolved?: boolean },
|
||||
) {
|
||||
const directive = extractShippingActionsDirective(String(content || ''));
|
||||
if (opts?.apiResolved) {
|
||||
return {
|
||||
buttons: normalizeApiShippingButtons(apiButtons),
|
||||
cleanedText: directive.cleanedText,
|
||||
fromDirective: false,
|
||||
};
|
||||
}
|
||||
if (directive.buttons.length) {
|
||||
return { buttons: directive.buttons, cleanedText: directive.cleanedText, fromDirective: true };
|
||||
}
|
||||
if (apiButtons?.length) {
|
||||
return { buttons: normalizeApiShippingButtons(apiButtons), cleanedText: directive.cleanedText, fromDirective: false };
|
||||
}
|
||||
return { buttons: [], cleanedText: directive.cleanedText, fromDirective: false };
|
||||
}
|
||||
|
||||
export function resolveShippingDecisionFromText(text: string, assistantContext: string): string | null {
|
||||
const normalized = text.trim();
|
||||
const direct: Record<string, string> = {
|
||||
更正映射: 'correct_inventory_mapping',
|
||||
更正列映射: 'correct_inventory_mapping',
|
||||
重新上传库存: 'reparse_inventory',
|
||||
重新上传: 'reparse_inventory',
|
||||
驳回: 'reject',
|
||||
取消: 'reject',
|
||||
重新解析: 'reparse',
|
||||
重新匹配: 'rematch',
|
||||
};
|
||||
if (direct[normalized]) return direct[normalized];
|
||||
if (normalized === '确认') {
|
||||
if (assistantContext.includes('字段对齐') || assistantContext.includes('field_alignment') || assistantContext.includes('库存字段对齐')) {
|
||||
return 'confirm_inventory_mapping';
|
||||
}
|
||||
return 'confirm';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* 出货聊天:任务编号提取(纯函数)。
|
||||
*
|
||||
* 从消息正文匹配 SHIPPING_TASK_ID_RE,或从侧栏会话标题模糊查找。
|
||||
*/
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
|
||||
export function findLatestShippingTaskId(msgs: Array<{ content?: string }>): string {
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const match = String(msgs[i]?.content || '').match(SHIPPING_TASK_ID_RE);
|
||||
if (match?.[0]) return match[0].toUpperCase();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function findHistorySessionForShippingTask(
|
||||
history: ChatSessionItem[],
|
||||
taskId: string,
|
||||
): ChatSessionItem | null {
|
||||
const needle = taskId.trim().toUpperCase();
|
||||
if (!needle) return null;
|
||||
return history.find((item) => String(item.title || '').toUpperCase().includes(needle)) || null;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* 出货聊天:消息文本净化与动作指令解析(纯函数,无 Vue 依赖)。
|
||||
*
|
||||
* - sanitizeShippingConversationText:隐藏后台状态 token,统一 task_id 展示
|
||||
* - extractShippingActionsDirective:解析 <!-- HXOPS_SHIPPING_ACTIONS --> 注释块
|
||||
* - normalizeShippingHeaderForDisplay:表头列名展示(空格转 NBSP)
|
||||
*/
|
||||
import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions';
|
||||
import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types';
|
||||
|
||||
export function sanitizeShippingConversationText(text: string, enabled: boolean): string {
|
||||
if (!enabled) return text;
|
||||
let result = String(text || '')
|
||||
.replace(/\btask_id\s*[::]/gi, '任务编号:')
|
||||
.replace(/\btask_id\b/gi, '任务编号');
|
||||
result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, '');
|
||||
result = result.replace(
|
||||
/\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi,
|
||||
'',
|
||||
);
|
||||
for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) {
|
||||
const quoted = new RegExp(`[「"'“”‘’]\\s*${token}\\s*[」"'“”‘’]`, 'gi');
|
||||
result = result.replace(quoted, '');
|
||||
result = result.replace(new RegExp(`\`${token}\``, 'gi'), '');
|
||||
}
|
||||
return result.replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
export function extractShippingActionsDirective(rawText: string): {
|
||||
cleanedText: string;
|
||||
buttons: ShippingActionButton[];
|
||||
} {
|
||||
const text = String(rawText || '');
|
||||
const re = /<!--\s*HXOPS_SHIPPING_ACTIONS\s*:\s*([\s\S]*?)\s*-->/gi;
|
||||
const buttons: ShippingActionButton[] = [];
|
||||
for (;;) {
|
||||
const m = re.exec(text);
|
||||
if (!m) break;
|
||||
const body = String(m[1] || '').trim();
|
||||
if (!body) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
if (Array.isArray(parsed)) {
|
||||
for (const item of parsed) {
|
||||
if (!item || typeof item !== 'object') continue;
|
||||
const id = String((item as Record<string, unknown>).id || '').trim();
|
||||
const label = String((item as Record<string, unknown>).label || '').trim();
|
||||
const message = String((item as Record<string, unknown>).message || '').trim();
|
||||
const variantRaw = String((item as Record<string, unknown>).variant || '').trim();
|
||||
const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger')
|
||||
? (variantRaw as ShippingActionVariant)
|
||||
: undefined;
|
||||
if (!id || !label || !message) continue;
|
||||
if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) {
|
||||
console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`);
|
||||
}
|
||||
buttons.push({ id, label, message, variant });
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed directive
|
||||
}
|
||||
}
|
||||
const cleaned = text.replace(re, '').trim();
|
||||
return { cleanedText: cleaned, buttons };
|
||||
}
|
||||
|
||||
export function normalizeShippingHeaderForDisplay(raw: unknown): string {
|
||||
const text = String(raw ?? '').replace(/\s+/g, ' ').trim();
|
||||
return text.replace(/ /g, '\u00A0');
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 出货聊天:库存上传后发给 Dify 的提示语、附件类型分类(纯函数)。
|
||||
*/
|
||||
export function buildShippingInventoryUploadPrompt(
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
fileName?: string,
|
||||
): string {
|
||||
const checkpoint = String(result?.checkpoint || '').trim();
|
||||
const hasAlignment = Boolean(result?.data && typeof result.data === 'object'
|
||||
&& (result.data as { field_alignment?: unknown }).field_alignment
|
||||
&& typeof (result.data as { field_alignment?: unknown }).field_alignment === 'object');
|
||||
const suggestOk = Boolean((result?.data as { suggest_ok?: boolean } | undefined)?.suggest_ok);
|
||||
const prefix = fileName ? `我已上传库存文件《${fileName}》` : '我已上传库存文件';
|
||||
if (checkpoint === 'map_infer') {
|
||||
if (suggestOk) {
|
||||
return `${prefix}。请继续处理库存列映射;如果系统已识别出完整映射,请直接应用映射,并展示字段对齐结果给我确认。`;
|
||||
}
|
||||
return `${prefix}。请继续解析库存列映射,并在拿到可用映射后展示字段对齐结果给我确认。`;
|
||||
}
|
||||
if (checkpoint === 'align_review' || hasAlignment) {
|
||||
return `${prefix}。请展示库存字段对齐结果,并引导我确认或更正映射。`;
|
||||
}
|
||||
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
|
||||
}
|
||||
|
||||
export function classifyShippingUploadFile(
|
||||
file: File,
|
||||
extractExt: (name: string) => string,
|
||||
): 'inventory' | 'notice' {
|
||||
const ext = extractExt(file.name || '').toLowerCase();
|
||||
if (['xlsx', 'xls', 'csv'].includes(ext)) return 'inventory';
|
||||
return 'notice';
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 出货聊天:人工决策提交(confirm/reject/reparse 等)与手工上传标记。
|
||||
*/
|
||||
import {
|
||||
autoProgressWorkspaceShippingTask,
|
||||
markWorkspaceShippingManualUploaded,
|
||||
submitWorkspaceShippingDecision,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingDecisionContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
loadHistory: () => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; success: (text: string) => void };
|
||||
t: (key: string, params?: Record<string, unknown>) => string;
|
||||
}
|
||||
|
||||
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
|
||||
const syncHistoryIfNeeded = async () => {
|
||||
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
|
||||
await ctx.loadHistory();
|
||||
} else if (ctx.conversationId.value) {
|
||||
const exists = ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value);
|
||||
if (!exists) await ctx.loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const executeShippingDecision = async (decision: string, displayText?: string) => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
const result =
|
||||
decision === 'confirm_inventory_mapping'
|
||||
? await autoProgressWorkspaceShippingTask(taskId)
|
||||
: await submitWorkspaceShippingDecision(taskId, decision);
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
const preview = result?.data?.schema_preview;
|
||||
const key = String(taskId || '').trim().toUpperCase();
|
||||
if (key && preview && typeof preview === 'object') {
|
||||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||||
[key]: preview,
|
||||
};
|
||||
}
|
||||
}
|
||||
const userText = (displayText || decision).trim();
|
||||
const assistantContent = formatShippingDecisionAssistantMessage(
|
||||
decision,
|
||||
result,
|
||||
taskId,
|
||||
ctx.t('chat.shippingNoticeDecisionDone'),
|
||||
);
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: assistantContent,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
if (result.message && !ctx.isShippingNoticeAgent.value) {
|
||||
ctx.msg.success(result.message);
|
||||
}
|
||||
await syncHistoryIfNeeded();
|
||||
void ctx.refreshShippingActions();
|
||||
if (decision === 'correct_inventory_mapping') {
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
}
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const executeShippingManualUpload = async (taskId: string, displayText?: string) => {
|
||||
try {
|
||||
const result = await markWorkspaceShippingManualUploaded(taskId);
|
||||
const userText = (displayText || '已在货代系统手工上传完成').trim();
|
||||
const assistantContent = [
|
||||
String(result.message || '已标记为手工上传货代系统完成。').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].join('\n');
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${userText}\n任务编号:${taskId}`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: assistantContent,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
shipping_actions_used: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
ctx.messages.value.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
await ctx.saveLocalMessageToBackend(userMsg, userText);
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, userText);
|
||||
void ctx.refreshShippingActions();
|
||||
return true;
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '标记手工上传失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
return { executeShippingDecision, executeShippingManualUpload };
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/**
|
||||
* 出货聊天:库存列映射表单(打开、应用、重传)。
|
||||
*/
|
||||
import { nextTick } from 'vue';
|
||||
import {
|
||||
applyWorkspaceShippingInventoryMapping,
|
||||
getWorkspaceShippingTask,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { buildShippingFieldAlignmentText, getShippingInventoryMappingPayload } from './shippingMapping';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { ShippingInventoryMappingFormPayload } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMappingFormContext {
|
||||
messages: Ref<ChatMessage[]>;
|
||||
chatScrollContainer: Ref<HTMLElement | null>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
}
|
||||
|
||||
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
|
||||
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
|
||||
const container = ctx.chatScrollContainer.value;
|
||||
if (!container) return false;
|
||||
let idx = -1;
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
if ((ctx.messages.value[i] as ChatMessage)?.type === 'shipping-inventory-mapping') {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (idx < 0) return false;
|
||||
await nextTick();
|
||||
await nextTick();
|
||||
const el = container.querySelector(`[data-msg-index="${idx}"]`) as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
return true;
|
||||
};
|
||||
|
||||
const openShippingInventoryMappingFormForTask = async (taskId: string): Promise<boolean> => {
|
||||
const id = String(taskId || '').trim().toUpperCase();
|
||||
if (!id) return false;
|
||||
const existingIdx = (() => {
|
||||
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
|
||||
const chatMsg = ctx.messages.value[i] as ChatMessage;
|
||||
if (chatMsg?.type !== 'shipping-inventory-mapping') continue;
|
||||
const payload = getShippingInventoryMappingPayload(chatMsg);
|
||||
if (payload?.taskId?.trim().toUpperCase() === id) return i;
|
||||
}
|
||||
return -1;
|
||||
})();
|
||||
if (existingIdx >= 0) {
|
||||
return scrollToLastShippingInventoryMapping();
|
||||
}
|
||||
const schemaPreview = ctx.shippingInventorySchemaPreviewCache.value[id];
|
||||
if (!schemaPreview || typeof schemaPreview !== 'object') {
|
||||
ctx.msg.warning('未找到表头预览,请重新上传库存文件后再点击“修改映射”');
|
||||
return false;
|
||||
}
|
||||
const detail = await getWorkspaceShippingTask(id).catch(() => null);
|
||||
const rawLines = Array.isArray((detail as { lines?: unknown[] } | null)?.lines)
|
||||
? (detail as { lines: unknown[] }).lines
|
||||
: [];
|
||||
const pickSku = (line: Record<string, unknown>) =>
|
||||
String(line?.sku || line?.SKU || line?.['AWS Sku'] || line?.['AWS SKU'] || '').trim();
|
||||
const skus = [...new Set(rawLines.map((line) => pickSku(line as Record<string, unknown>)).filter(Boolean))].slice(0, 40);
|
||||
const suggested = (schemaPreview as { suggested_mapping?: Record<string, string> }).suggested_mapping || {};
|
||||
const mappingMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'shipping-inventory-mapping',
|
||||
content: [
|
||||
'请用下拉框选择库存列映射(必须从表头中选择)。',
|
||||
`任务编号:${id}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
payload: {
|
||||
taskId: id,
|
||||
schema_preview: schemaPreview,
|
||||
order: { line_count: rawLines.length, skus },
|
||||
form: {
|
||||
sku: String(suggested?.sku || '').trim(),
|
||||
available_qty: String(suggested?.available_qty || '').trim(),
|
||||
reservation_id: String(suggested?.reservation_id || '').trim(),
|
||||
},
|
||||
applying: false,
|
||||
} as ShippingInventoryMappingFormPayload,
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(mappingMsg);
|
||||
await ctx.saveLocalMessageToBackend(mappingMsg);
|
||||
await scrollToLastShippingInventoryMapping();
|
||||
return true;
|
||||
};
|
||||
|
||||
const applyShippingInventoryMappingForm = async (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
if (payload.applying) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('未找到任务编号');
|
||||
return;
|
||||
}
|
||||
const mapping: Record<string, string> = {
|
||||
sku: String(payload.form?.sku || '').trim(),
|
||||
available_qty: String(payload.form?.available_qty || '').trim(),
|
||||
reservation_id: String(payload.form?.reservation_id || '').trim(),
|
||||
};
|
||||
if (!mapping.sku || !mapping.available_qty) {
|
||||
ctx.msg.warning('请先选择 SKU 列 与 可用数量列');
|
||||
return;
|
||||
}
|
||||
if (!mapping.reservation_id) {
|
||||
delete mapping.reservation_id;
|
||||
}
|
||||
payload.applying = true;
|
||||
try {
|
||||
const result = await applyWorkspaceShippingInventoryMapping(taskId, mapping);
|
||||
const alignmentText = buildShippingFieldAlignmentText(result);
|
||||
const hint = alignmentText || String(result.message || '').trim();
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
'映射已应用并解析库存。',
|
||||
`任务编号:${taskId}`,
|
||||
hint,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '应用映射失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
} finally {
|
||||
payload.applying = false;
|
||||
await ctx.saveLocalMessageToBackend(msgObj);
|
||||
}
|
||||
};
|
||||
|
||||
const reuploadShippingInventoryFromMappingForm = (msgObj: ChatMessage) => {
|
||||
const payload = getShippingInventoryMappingPayload(msgObj);
|
||||
if (!payload) return;
|
||||
const taskId = String(payload.taskId || '').trim();
|
||||
if (!taskId) return;
|
||||
ctx.pendingShippingUploadTaskId.value = taskId;
|
||||
ctx.shippingInventoryPickerRef.value?.click();
|
||||
};
|
||||
|
||||
return {
|
||||
openShippingInventoryMappingFormForTask,
|
||||
applyShippingInventoryMappingForm,
|
||||
reuploadShippingInventoryFromMappingForm,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* 出货聊天:消息气泡动作按钮与菜单项点击分发。
|
||||
*
|
||||
* 按 action.id 路由到 API 调用、决策提交、文件选择器或 Dify 菜单消息。
|
||||
*/
|
||||
import {
|
||||
generateWorkspaceShippingExcel,
|
||||
matchWorkspaceShippingInventory,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
|
||||
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingMenuHandlerContext {
|
||||
isThinking: Ref<boolean>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
newLocalMessageId: (prefix: string) => string;
|
||||
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
openShippingInventoryMappingFormForTask: (taskId: string) => Promise<boolean>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
|
||||
const handleShippingMenuAction = async (
|
||||
action: { id?: string; message: string },
|
||||
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
|
||||
) => {
|
||||
if (ctx.isThinking.value) return;
|
||||
if (action.id === 'refresh') {
|
||||
await ctx.sendShippingMenuMessage(action.message || '刷新');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'download_excel') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await downloadWorkspaceShippingExcelFile(taskId);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '下载 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'generate_excel') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await generateWorkspaceShippingExcel(taskId);
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${action.message || '生成发货 Excel'}(任务编号:${taskId})`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '生成发货 Excel');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '生成发货 Excel');
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '生成发货 Excel 失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'edit_inventory_mapping') {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.openShippingInventoryMappingFormForTask(taskId);
|
||||
return;
|
||||
}
|
||||
if (action.id === 'upload_inventory_file') {
|
||||
ctx.openShippingInventoryPicker();
|
||||
return;
|
||||
}
|
||||
if (action.id === 'match_inventory') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await matchWorkspaceShippingInventory(taskId);
|
||||
const userMsg: ChatMessage = {
|
||||
role: 'user',
|
||||
type: 'text',
|
||||
content: `${action.message || '匹配库存'}(任务编号:${taskId})`,
|
||||
local_id: ctx.newLocalMessageId('shipping-user'),
|
||||
local_only: true,
|
||||
};
|
||||
const assistantMsg: ChatMessage = {
|
||||
role: 'assistant',
|
||||
type: 'text',
|
||||
content: [
|
||||
String(result.message || '').trim(),
|
||||
`任务编号:${taskId}`,
|
||||
].filter(Boolean).join('\n'),
|
||||
local_id: ctx.newLocalMessageId('shipping-assistant'),
|
||||
local_only: true,
|
||||
};
|
||||
ctx.messages.value.push(userMsg, assistantMsg);
|
||||
await ctx.saveLocalMessageToBackend(userMsg, action.message || '匹配库存');
|
||||
await ctx.saveLocalMessageToBackend(assistantMsg, action.message || '匹配库存');
|
||||
void ctx.refreshShippingActions();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : '匹配库存失败';
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action.id === 'mark_manual_uploaded') {
|
||||
if (chatMsg?.shipping_actions_used) return;
|
||||
if (chatMsg) chatMsg.shipping_actions_used = true;
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return;
|
||||
}
|
||||
await ctx.executeShippingManualUpload(taskId, action.message || '已在货代系统手工上传完成');
|
||||
return;
|
||||
}
|
||||
if (action.id === 'paste_inventory_json') {
|
||||
ctx.msg.info(ctx.t('chat.shippingNoticePasteHint'));
|
||||
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);
|
||||
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: { id?: string; message: string },
|
||||
) => {
|
||||
await handleShippingMenuAction(action, chatMsg);
|
||||
};
|
||||
|
||||
return { handleShippingMenuAction, handleShippingActionClick };
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 出货聊天:助手消息动作按钮刷新(有状态 composable 工厂)。
|
||||
*
|
||||
* 按 taskId 拉取 getShippingChatActions,写入 messages[].shipping_actions;
|
||||
* 终态 checkpoint 时清除所有按钮。
|
||||
*/
|
||||
import {
|
||||
getShippingChatActions,
|
||||
listWorkspaceShippingTasks,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { SHIPPING_TERMINAL_CHECKPOINTS } from '@/constants/shippingNoticeActions';
|
||||
import { SHIPPING_TASK_ID_RE } from '../constants/shipping';
|
||||
import { findLatestShippingTaskId } from './shippingTaskId';
|
||||
import { resolveShippingActionButtons } from './shippingMenu';
|
||||
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
|
||||
import type { ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingRefreshContext {
|
||||
isShippingNoticeAgent: ComputedRef<boolean>;
|
||||
messages: Ref<ChatMessage[]>;
|
||||
conversationId: Ref<string | null>;
|
||||
isThinking: Ref<boolean>;
|
||||
history: Ref<ChatSessionItem[]>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingTaskIdFromQuery: ComputedRef<string>;
|
||||
shippingConversationTaskIdCache: Ref<Record<string, string>>;
|
||||
}
|
||||
|
||||
export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>, index: number): boolean {
|
||||
return msgs.slice(index + 1).some((item) => item.role === 'user');
|
||||
}
|
||||
|
||||
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
|
||||
let shippingActionsRequestSeq = 0;
|
||||
|
||||
const refreshShippingActions = async () => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return;
|
||||
const msgs = ctx.messages.value;
|
||||
if (!msgs.length) return;
|
||||
const cid = String(ctx.conversationId.value || '').trim();
|
||||
const historyTaskId = (() => {
|
||||
if (!cid) return '';
|
||||
const session = ctx.history.value.find((item) => String(item.conversation_id || '') === cid);
|
||||
const title = String(session?.title || '');
|
||||
const match = title.match(SHIPPING_TASK_ID_RE);
|
||||
return match?.[0] ? match[0].toUpperCase() : '';
|
||||
})();
|
||||
let taskId = findLatestShippingTaskId(msgs)
|
||||
|| ctx.resolvedShippingTaskId.value
|
||||
|| ctx.shippingTaskIdFromQuery.value
|
||||
|| historyTaskId;
|
||||
if (!taskId && cid && !ctx.isThinking.value) {
|
||||
const cached = ctx.shippingConversationTaskIdCache.value[cid];
|
||||
if (cached) {
|
||||
taskId = cached;
|
||||
} else {
|
||||
try {
|
||||
const rows = await listWorkspaceShippingTasks({ limit: 500 });
|
||||
const hit = rows.find((row) => String(row.conversation_id || '') === cid);
|
||||
const taskNo = hit?.task_no ? String(hit.task_no).trim().toUpperCase() : '';
|
||||
if (taskNo) {
|
||||
ctx.shippingConversationTaskIdCache.value = { ...ctx.shippingConversationTaskIdCache.value, [cid]: taskNo };
|
||||
taskId = taskNo;
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
}
|
||||
}
|
||||
}
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
let apiButtons: Array<{ id: string; label: string; message: string; variant?: string }> | null = null;
|
||||
let apiCheckpoint: string | null = null;
|
||||
let apiResolved = false;
|
||||
if (taskId && !ctx.isThinking.value) {
|
||||
const seq = ++shippingActionsRequestSeq;
|
||||
try {
|
||||
const data = await getShippingChatActions(taskId);
|
||||
if (seq === shippingActionsRequestSeq) {
|
||||
apiResolved = true;
|
||||
apiCheckpoint = data.checkpoint ? String(data.checkpoint) : null;
|
||||
apiButtons = data.action_buttons?.length ? data.action_buttons : null;
|
||||
}
|
||||
} catch {
|
||||
// fall back to content-based buttons
|
||||
}
|
||||
}
|
||||
if (apiResolved && apiCheckpoint && SHIPPING_TERMINAL_CHECKPOINTS.has(apiCheckpoint)) {
|
||||
msgs.forEach((rawMsg) => {
|
||||
const m = rawMsg as ChatMessage & { shipping_actions?: unknown };
|
||||
if (m.role === 'assistant') {
|
||||
m.shipping_actions = undefined;
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
let lastOpenAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const item = msgs[i];
|
||||
if (item?.role !== 'assistant') continue;
|
||||
if (assistantMessageHasLaterUserReply(msgs, i)) continue;
|
||||
lastOpenAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
let lastAssistantIndex = -1;
|
||||
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
||||
const item = msgs[i];
|
||||
if (item?.role === 'assistant') {
|
||||
lastAssistantIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const targetAssistantIndex = lastOpenAssistantIndex >= 0 ? lastOpenAssistantIndex : lastAssistantIndex;
|
||||
msgs.forEach((rawMsg, index) => {
|
||||
const chatMsg = rawMsg as ChatMessage & {
|
||||
shipping_actions_used?: boolean;
|
||||
shipping_actions?: ShippingActionButton[];
|
||||
};
|
||||
if (chatMsg.role !== 'assistant' || chatMsg.shipping_actions_used) {
|
||||
return;
|
||||
}
|
||||
if (chatMsg.type && !['text', undefined].includes(chatMsg.type)) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
if (assistantMessageHasLaterUserReply(msgs, index) && index !== targetAssistantIndex) {
|
||||
chatMsg.shipping_actions = undefined;
|
||||
return;
|
||||
}
|
||||
let buttons: ShippingActionButton[] = [];
|
||||
if (index === targetAssistantIndex) {
|
||||
const resolved = resolveShippingActionButtons(
|
||||
String(chatMsg.content || ''),
|
||||
apiResolved ? (apiButtons ?? []) : null,
|
||||
{ apiResolved },
|
||||
);
|
||||
if (resolved.fromDirective) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
} else if (!apiResolved) {
|
||||
const resolved = resolveShippingActionButtons(String(chatMsg.content || ''), null);
|
||||
if (resolved.fromDirective) {
|
||||
chatMsg.content = resolved.cleanedText;
|
||||
}
|
||||
buttons = resolved.buttons;
|
||||
}
|
||||
chatMsg.shipping_actions = buttons.length ? buttons : undefined;
|
||||
});
|
||||
};
|
||||
|
||||
return { refreshShippingActions };
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* 出货聊天:handleSend 前置拦截(菜单数字、决策文本、列映射、附件自动流程)。
|
||||
*
|
||||
* 返回 true 表示已消费本次发送,ChatView 不再走默认 Dify 流程。
|
||||
*/
|
||||
import { applyWorkspaceShippingInventoryMapping, generateWorkspaceShippingExcel } 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,
|
||||
parseShippingColumnMappingFromText,
|
||||
} from './shippingIntents';
|
||||
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
|
||||
import { classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { ensureShippingHistorySynced } from './shippingConversation';
|
||||
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<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>;
|
||||
currentAgentId: ComputedRef<number>;
|
||||
selectedKb: Ref<string>;
|
||||
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
lastAssistantMessageContent: () => string;
|
||||
sendMessage: (
|
||||
content: string,
|
||||
agentId: number,
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
) => Promise<void>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadHistory: () => Promise<void>;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
pushShippingLocalUserMessage: (text: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
openShippingInventoryPicker: () => boolean;
|
||||
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
|
||||
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
|
||||
handleShippingAutoUploadFile: (file: File) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
shippingSuggestedPrompt: ComputedRef<string>;
|
||||
msg: { warning: (text: string) => void; info: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
|
||||
const tryHandleShippingAttachmentAutoFlow = async (
|
||||
textOrEvent: string | Event | undefined,
|
||||
_content: string,
|
||||
trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
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<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 {
|
||||
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) {
|
||||
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
|
||||
let files: ChatUploadFileSpec[] = [];
|
||||
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
|
||||
try {
|
||||
files = await ctx.buildFileSpecsForSend();
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : 'unknown error';
|
||||
ctx.msg.warning(`附件处理失败:${errorMessage}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
ctx.attachments.value = [];
|
||||
await ctx.sendMessage(prompt, ctx.currentAgentId.value, ctx.selectedKb.value, files);
|
||||
await ensureShippingHistorySynced({
|
||||
conversationId: ctx.conversationId,
|
||||
history: ctx.history,
|
||||
loadHistory: ctx.loadHistory,
|
||||
getActiveShippingTaskId: ctx.getActiveShippingTaskId,
|
||||
currentAgentId: ctx.currentAgentId,
|
||||
selectedKb: ctx.selectedKb,
|
||||
sendMessage: ctx.sendMessage,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const tryHandleShippingSend = async (
|
||||
textOrEvent: string | Event | undefined,
|
||||
content: string,
|
||||
_trimmed: string,
|
||||
): Promise<boolean> => {
|
||||
if (!ctx.isShippingNoticeAgent.value) return false;
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* 出货聊天:库存/发货通知文件上传、隐藏 file input、附件建议提示。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import {
|
||||
createWorkspaceShippingTask,
|
||||
createWorkspaceShippingTaskFromNotice,
|
||||
uploadWorkspaceShippingInventory,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import { extractExt } from '../constants/shipping';
|
||||
import { buildShippingInventoryUploadPrompt, classifyShippingUploadFile } from './shippingUploadPrompt';
|
||||
import type { PendingAttachment } from '../types/shipping.types';
|
||||
import type { Ref } from 'vue';
|
||||
|
||||
export interface ShippingUploadHandlerContext {
|
||||
conversationId: Ref<string | null>;
|
||||
attachments: Ref<PendingAttachment[]>;
|
||||
input: Ref<string>;
|
||||
shippingAutoFlowRequested: Ref<boolean>;
|
||||
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
|
||||
pendingShippingUploadTaskId: Ref<string>;
|
||||
resolvedShippingTaskId: Ref<string>;
|
||||
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
|
||||
getActiveShippingTaskId: () => string;
|
||||
sendShippingMenuMessage: (message: string) => Promise<void>;
|
||||
pushShippingLocalAssistantMessage: (text: string) => Promise<void>;
|
||||
refreshShippingActions: () => Promise<void>;
|
||||
msg: { warning: (text: string) => void };
|
||||
t: (key: string) => string;
|
||||
}
|
||||
|
||||
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
|
||||
const continueShippingInventoryUploadWithDify = async (
|
||||
taskId: string,
|
||||
result: Record<string, unknown> | null | undefined,
|
||||
fileName?: string,
|
||||
) => {
|
||||
const key = String(taskId || '').trim().toUpperCase();
|
||||
const schemaPreview = (result?.data as { schema_preview?: unknown } | undefined)?.schema_preview;
|
||||
if (key && schemaPreview && typeof schemaPreview === 'object') {
|
||||
ctx.shippingInventorySchemaPreviewCache.value = {
|
||||
...ctx.shippingInventorySchemaPreviewCache.value,
|
||||
[key]: schemaPreview,
|
||||
};
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
await ctx.sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
|
||||
};
|
||||
|
||||
const handleShippingAutoUploadFile = async (file: File) => {
|
||||
const kind = classifyShippingUploadFile(file, extractExt);
|
||||
if (kind === 'inventory') {
|
||||
let taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
const created = await createWorkspaceShippingTask({
|
||||
source_type: 'manual',
|
||||
conversation_id: String(ctx.conversationId.value || '').trim() || undefined,
|
||||
});
|
||||
taskId = String(created.task_id || '').trim();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning('自动创建发货任务失败');
|
||||
return;
|
||||
}
|
||||
}
|
||||
ctx.resolvedShippingTaskId.value = taskId;
|
||||
const result = await uploadWorkspaceShippingInventory(taskId, file);
|
||||
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
|
||||
return;
|
||||
}
|
||||
const result = await createWorkspaceShippingTaskFromNotice(
|
||||
file,
|
||||
String(ctx.conversationId.value || '').trim() || undefined,
|
||||
);
|
||||
const taskId = String(result.task_id || '').trim();
|
||||
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
|
||||
const hint = String(result.message || '').trim();
|
||||
const status = String((result as { status?: string }).status || '').trim();
|
||||
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
|
||||
await ctx.pushShippingLocalAssistantMessage(
|
||||
[
|
||||
hint || `已处理发货通知附件:${file.name}`,
|
||||
taskId ? `任务编号:${taskId}` : '',
|
||||
tail,
|
||||
].filter(Boolean).join('\n'),
|
||||
);
|
||||
void ctx.refreshShippingActions();
|
||||
};
|
||||
|
||||
const openShippingInventoryPicker = (): boolean => {
|
||||
const taskId = ctx.getActiveShippingTaskId();
|
||||
if (!taskId) {
|
||||
ctx.msg.warning(ctx.t('chat.shippingNoticeMissingTaskId'));
|
||||
return false;
|
||||
}
|
||||
ctx.pendingShippingUploadTaskId.value = taskId;
|
||||
ctx.shippingInventoryPickerRef.value?.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
const handleShippingInventorySelected = async (event: Event) => {
|
||||
const fileInput = event.target as HTMLInputElement;
|
||||
const file = fileInput.files?.[0];
|
||||
fileInput.value = '';
|
||||
const taskId = ctx.pendingShippingUploadTaskId.value;
|
||||
ctx.pendingShippingUploadTaskId.value = '';
|
||||
if (!file || !taskId) return;
|
||||
try {
|
||||
const result = await uploadWorkspaceShippingInventory(taskId, file);
|
||||
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
|
||||
} catch (e: unknown) {
|
||||
const errorMessage = e instanceof Error ? e.message : ctx.t('chat.shippingNoticeUploadFailed');
|
||||
ctx.msg.warning(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
const shippingSuggestedPrompt = computed(() => {
|
||||
const first = ctx.attachments.value.find((a) => a.kind === 'local') as
|
||||
| Extract<PendingAttachment, { kind: 'local' }>
|
||||
| undefined;
|
||||
if (!first) return '';
|
||||
const kind = classifyShippingUploadFile(first.file, extractExt);
|
||||
if (kind === 'inventory') return '上传库存并进入字段对齐';
|
||||
return '解析发货通知并创建任务';
|
||||
});
|
||||
|
||||
const useShippingSuggestedPrompt = () => {
|
||||
const prompt = shippingSuggestedPrompt.value;
|
||||
if (!prompt) return;
|
||||
ctx.input.value = prompt;
|
||||
ctx.shippingAutoFlowRequested.value = true;
|
||||
};
|
||||
|
||||
return {
|
||||
handleShippingAutoUploadFile,
|
||||
openShippingInventoryPicker,
|
||||
handleShippingInventorySelected,
|
||||
shippingSuggestedPrompt,
|
||||
useShippingSuggestedPrompt,
|
||||
};
|
||||
}
|
||||
@@ -1,21 +1,58 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { ref } from 'vue';
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
|
||||
/**
|
||||
* features/chat/stores/chat.store.ts
|
||||
* 聊天域共享状态:当前 agent、侧栏折叠等(会话列表逐步迁入)。
|
||||
* 聊天域跨页面共享状态:当前 Agent、侧栏折叠、按 Agent 缓存的会话列表。
|
||||
*/
|
||||
export const useChatStore = defineStore('chat', () => {
|
||||
const currentAgentId = ref<number | null>(null);
|
||||
/** 桌面端 ChatSidebar 是否收起 */
|
||||
const sidebarCollapsed = ref(false);
|
||||
/** 按 Agent ID 缓存侧栏会话列表,切换回来时先展示缓存再后台刷新 */
|
||||
const sessionHistoryByAgent = ref<Record<number, ChatSessionItem[]>>({});
|
||||
|
||||
const setCurrentAgentId = (agentId: number | null): void => {
|
||||
currentAgentId.value = agentId;
|
||||
};
|
||||
|
||||
const getSessionHistory = (agentId: number): ChatSessionItem[] | null => {
|
||||
const items = sessionHistoryByAgent.value[agentId];
|
||||
return Array.isArray(items) ? items : null;
|
||||
};
|
||||
|
||||
const setSessionHistory = (agentId: number, items: ChatSessionItem[]): void => {
|
||||
sessionHistoryByAgent.value = {
|
||||
...sessionHistoryByAgent.value,
|
||||
[agentId]: items,
|
||||
};
|
||||
};
|
||||
|
||||
const patchSessionHistory = (agentId: number, items: ChatSessionItem[]): void => {
|
||||
setSessionHistory(agentId, items);
|
||||
};
|
||||
|
||||
const clearSessionHistoryForAgent = (agentId: number): void => {
|
||||
const next = { ...sessionHistoryByAgent.value };
|
||||
delete next[agentId];
|
||||
sessionHistoryByAgent.value = next;
|
||||
};
|
||||
|
||||
/** Agent 切换或离开对话页时重置页面级 UI 偏好 */
|
||||
const resetPageUiState = () => {
|
||||
sidebarCollapsed.value = false;
|
||||
};
|
||||
|
||||
return {
|
||||
currentAgentId,
|
||||
sidebarCollapsed,
|
||||
sessionHistoryByAgent,
|
||||
setCurrentAgentId,
|
||||
getSessionHistory,
|
||||
setSessionHistory,
|
||||
patchSessionHistory,
|
||||
clearSessionHistoryForAgent,
|
||||
resetPageUiState,
|
||||
};
|
||||
});
|
||||
@@ -2,6 +2,9 @@
|
||||
* features/chat/types/chat.types.ts
|
||||
* 聊天域核心类型定义。
|
||||
*/
|
||||
import type { LeaveAgentOption } from './leave.types';
|
||||
|
||||
export type { LeaveAgentOption };
|
||||
|
||||
export interface RetrieverResource {
|
||||
dataset_name?: string;
|
||||
@@ -70,18 +73,6 @@ export interface SourceFileLink {
|
||||
actualExt?: string;
|
||||
}
|
||||
|
||||
export interface LeaveAgentOption {
|
||||
uid: string;
|
||||
employeeId: string;
|
||||
name: string;
|
||||
jobtitle?: string;
|
||||
jobtitleName?: string;
|
||||
departmentid?: string;
|
||||
subcompanyid1?: string;
|
||||
departmentName?: string;
|
||||
subcompanyName?: string;
|
||||
}
|
||||
|
||||
export interface OaEmployeesResponse {
|
||||
items: LeaveAgentOption[];
|
||||
total: number;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* features/chat/types/leave.types.ts
|
||||
* 请假(OA)流程相关类型:表单、确认单、结果与选人。
|
||||
*/
|
||||
|
||||
/** 请假表单字段(与 OA workflow 字段对齐) */
|
||||
export interface LeaveRequestFormData {
|
||||
applicantName: string;
|
||||
employeeId: string;
|
||||
applicantUid: string;
|
||||
applicantJobTitle?: string;
|
||||
applicantJobTitleName?: string;
|
||||
applicantDepartmentId?: string;
|
||||
applicantSubCompanyId1?: string;
|
||||
applicantDepartmentName?: string;
|
||||
applicantSubCompanyName?: string;
|
||||
applyTime: string;
|
||||
fillerName: string;
|
||||
fillerJobTitle?: string;
|
||||
fillerJobTitleName?: string;
|
||||
fillerDepartmentId?: string;
|
||||
fillerSubCompanyId1?: string;
|
||||
fillerDepartmentName?: string;
|
||||
fillerSubCompanyName?: string;
|
||||
agentUid: string;
|
||||
agentEmployeeId: string;
|
||||
agentName: string;
|
||||
agentJobTitle?: string;
|
||||
agentJobTitleName?: string;
|
||||
agentDepartmentId?: string;
|
||||
agentSubCompanyId1?: string;
|
||||
agentDepartmentName?: string;
|
||||
agentSubCompanyName?: string;
|
||||
leaveType: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
durationHours: number;
|
||||
isOutOfOffice: 0 | 1 | null;
|
||||
isWorkInjury: 0 | 1 | null;
|
||||
}
|
||||
|
||||
/** leave-form 消息 payload */
|
||||
export interface LeaveFormPayload {
|
||||
formId: string;
|
||||
form: LeaveRequestFormData;
|
||||
submitting: boolean;
|
||||
confirmationGenerated: boolean;
|
||||
}
|
||||
|
||||
/** leave-confirmation 消息 payload */
|
||||
export interface LeaveConfirmationPayload {
|
||||
formId: string;
|
||||
form: LeaveRequestFormData;
|
||||
submitting: boolean;
|
||||
confirmed?: boolean;
|
||||
}
|
||||
|
||||
/** leave-result 消息 payload */
|
||||
export interface LeaveResultPayload {
|
||||
formId: string;
|
||||
success: boolean;
|
||||
referenceNo: string;
|
||||
submittedAt: string;
|
||||
requestName?: string;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
/** OA 员工列表项(请假代理人 / 申请人) */
|
||||
export interface LeaveAgentOption {
|
||||
uid: string;
|
||||
employeeId: string;
|
||||
name: string;
|
||||
jobtitle?: string;
|
||||
jobtitleName?: string;
|
||||
departmentid?: string;
|
||||
subcompanyid1?: string;
|
||||
departmentName?: string;
|
||||
subcompanyName?: string;
|
||||
}
|
||||
|
||||
/** 从用户自然语言中解析出的请假要素 */
|
||||
export interface ExtractedLeaveInfo {
|
||||
leaveType: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
durationHours: number;
|
||||
}
|
||||
|
||||
export interface LeaveBalanceInfo {
|
||||
has_balance: boolean;
|
||||
leave_type_label: string;
|
||||
year: number;
|
||||
total_hours: number | null;
|
||||
used_hours: number | null;
|
||||
remaining_hours: number | null;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* features/chat/types/shipping.api.types.ts
|
||||
* 货代发货 Agent / 工作台发货任务 API 契约类型。
|
||||
*/
|
||||
export interface ShippingTaskSummary {
|
||||
id: number;
|
||||
task_no: string;
|
||||
source_type: string;
|
||||
customer_name?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
match_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
conversation_id?: string | null;
|
||||
export_file_name?: string | null;
|
||||
freight_ref_no?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingTaskEvent {
|
||||
event_type: string;
|
||||
detail_json?: Record<string, unknown> | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface ShippingTaskDetail extends ShippingTaskSummary {
|
||||
customer_code?: string | null;
|
||||
ship_to?: string | null;
|
||||
po_number?: string | null;
|
||||
required_date?: string | null;
|
||||
lines: Array<Record<string, unknown>>;
|
||||
shortage?: Record<string, unknown> | null;
|
||||
line_results?: Array<Record<string, unknown>>;
|
||||
parse_confidence?: number | null;
|
||||
error_message?: string | null;
|
||||
events: ShippingTaskEvent[];
|
||||
}
|
||||
|
||||
export interface ShippingChatAction {
|
||||
id: string;
|
||||
label: string;
|
||||
message: string;
|
||||
variant: 'primary' | 'secondary' | 'danger';
|
||||
}
|
||||
|
||||
export interface ShippingChatActionsResponse {
|
||||
task_no: string;
|
||||
checkpoint?: string | null;
|
||||
process_status: string;
|
||||
review_status?: string | null;
|
||||
pending_human_reason?: string | null;
|
||||
action_buttons: ShippingChatAction[];
|
||||
}
|
||||
|
||||
export interface ShippingInventoryUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ShippingTaskCreateResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ShippingNoticeUploadResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
human_options?: string[];
|
||||
}
|
||||
|
||||
export interface ShippingDecisionResponse {
|
||||
status: string;
|
||||
message?: string;
|
||||
task_id?: string;
|
||||
checkpoint?: string;
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* features/chat/types/shipping.types.ts
|
||||
* 发货通知(出货)流程相关类型:库存映射表单、菜单动作与附件。
|
||||
*/
|
||||
|
||||
export type ShippingActionVariant = 'primary' | 'secondary' | 'danger';
|
||||
|
||||
export type ShippingMenuAction = 'upload' | 'paste' | 'retry_rpa' | 'confirm' | 'reparse' | 'reject';
|
||||
|
||||
export type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||
|
||||
/** 待发送附件(本地文件或远程 URL) */
|
||||
export type PendingAttachment =
|
||||
| { id: string; kind: 'local'; file: File; type: ChatUploadFileType }
|
||||
| { id: string; kind: 'remote'; url: string; type: ChatUploadFileType };
|
||||
|
||||
export type ChatUploadFileSpec =
|
||||
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
|
||||
| { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string };
|
||||
|
||||
/** 库存 Excel 表头预览(后端 schema_preview 字段) */
|
||||
export interface ShippingSchemaPreview {
|
||||
header_row_index?: number;
|
||||
headers?: string[];
|
||||
sample_rows?: unknown[][];
|
||||
suggested_mapping?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** 库存列映射表单消息 payload(type=shipping-inventory-mapping) */
|
||||
export interface ShippingInventoryMappingFormPayload {
|
||||
taskId: string;
|
||||
schema_preview: ShippingSchemaPreview;
|
||||
order: { line_count: number; skus: string[] };
|
||||
form: { sku: string; available_qty: string; reservation_id: string };
|
||||
applying?: boolean;
|
||||
}
|
||||
|
||||
export interface ShippingActionButton {
|
||||
id: string;
|
||||
label: string;
|
||||
message: string;
|
||||
variant?: ShippingActionVariant;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/** 去除模型 reasoning 前奏,供 Markdown 展示与出货模块使用 */
|
||||
export const stripReasoningPrelude = (text: string) => {
|
||||
if (!text) return '';
|
||||
let cleaned = text
|
||||
.replace(/<think[\s\S]*?<\/think>/gi, '')
|
||||
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
|
||||
.trim();
|
||||
|
||||
const reasoningMarkers = [
|
||||
'让我分析',
|
||||
'根据应答生成规则',
|
||||
'分析知识库返回的内容',
|
||||
'我需要直接给出答案',
|
||||
'思考过程',
|
||||
'推理过程',
|
||||
];
|
||||
const hasReasoningMarker = reasoningMarkers.some((marker) => cleaned.includes(marker));
|
||||
if (!hasReasoningMarker) return cleaned;
|
||||
|
||||
const headingMatch = cleaned.match(/(^|\n)\s{0,3}#{1,6}\s+/);
|
||||
if (headingMatch && typeof headingMatch.index === 'number') {
|
||||
const start = headingMatch.index + (headingMatch[1] ? headingMatch[1].length : 0);
|
||||
cleaned = cleaned.slice(start).trim();
|
||||
}
|
||||
return cleaned;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user