Merge branch 'dev' into hugo-shipping-notice
# Conflicts: # .env.dev # .env.test # backend/app/api/__init__.py # docs/funclist.md # frontend/src/features/chat/composables/useChatPage.ts
This commit is contained in:
commit
f72c1c9f0e
101 files changed
+11163
-334
No files matched your search
@@ -1,10 +1,11 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/api/chat.api.ts
|
||||
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import type {
|
||||
AssetHistorySearchResult,
|
||||
ChatCrossAgentHistoryItem,
|
||||
ChatMessage,
|
||||
ChatQueryPreviewPage,
|
||||
@@ -90,4 +91,17 @@ export const getChatQueryPreviewPage = (
|
||||
return requestJson<ChatQueryPreviewPage>(`/api/chat/query-preview/${chatLogId}?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export const searchAssetHistoryFiles = (
|
||||
agentId: number,
|
||||
query: { asset_id?: string; asset_name?: string; limit?: number },
|
||||
) => {
|
||||
const qs = new URLSearchParams({
|
||||
agent_id: String(agentId),
|
||||
});
|
||||
if (query.asset_id) qs.set('asset_id', query.asset_id);
|
||||
if (query.asset_name) qs.set('asset_name', query.asset_name);
|
||||
if (query.limit) qs.set('limit', String(query.limit));
|
||||
return requestJson<AssetHistorySearchResult>(`/api/chat/asset-history/search?${qs.toString()}`, auth());
|
||||
};
|
||||
|
||||
export type { ChatSessionItem, ChatCrossAgentHistoryItem };
|
||||
@@ -0,0 +1,91 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/components/ChatAssetHistoryDialog.vue
|
||||
* 用途:展示固定资产履历候选文件列表,并复用既有文件预览弹窗打开具体履历。
|
||||
* 依赖:聊天页 useChatPage 提供的查询状态与打开预览回调。
|
||||
* 逻辑:用户点击资产编号后打开;先显示检索状态,再列出共享盘匹配文件,点击单条文件进入预览。
|
||||
*/
|
||||
import { computed } from 'vue';
|
||||
import { ExternalLink, FileText, Loader2, X } from 'lucide-vue-next';
|
||||
import type { AssetHistoryFileItem } from '../types/chat.types';
|
||||
|
||||
const open = defineModel<boolean>('open', { required: true });
|
||||
|
||||
const props = defineProps<{
|
||||
loading: boolean;
|
||||
error: string;
|
||||
assetId: string;
|
||||
assetName: string;
|
||||
items: AssetHistoryFileItem[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
openPreview: [item: AssetHistoryFileItem];
|
||||
}>();
|
||||
|
||||
const titleText = computed(() => props.assetId || props.assetName || '资产履历');
|
||||
</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,900px)] max-w-[900px] flex-col">
|
||||
<div class="dialog-header">
|
||||
<div>
|
||||
<h3 class="section-title">资产履历</h3>
|
||||
<p class="section-desc mt-1">当前资产:{{ titleText }}</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 v-if="loading" class="flex h-56 items-center justify-center text-sm text-muted">
|
||||
<Loader2 class="mr-2 h-5 w-5 animate-spin text-brand-500" />
|
||||
正在检索共享盘履历文件...
|
||||
</div>
|
||||
<div v-else-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
|
||||
{{ error }}
|
||||
</div>
|
||||
<div
|
||||
v-else-if="items.length === 0"
|
||||
class="flex h-56 items-center justify-center rounded-2xl border border-dashed border-default bg-surface-soft text-sm text-muted"
|
||||
>
|
||||
未找到匹配的履历文件
|
||||
</div>
|
||||
<div v-else class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
|
||||
<div
|
||||
v-for="item in items"
|
||||
:key="item.path"
|
||||
class="flex items-start justify-between gap-3 border-b border-default px-4 py-4 last:border-b-0"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 text-sm font-semibold text-primary">
|
||||
<FileText class="h-4 w-4 shrink-0 text-brand-500" />
|
||||
<span class="truncate">{{ item.name }}</span>
|
||||
</div>
|
||||
<div class="mt-1 break-all text-xs text-secondary">{{ item.relative_path }}</div>
|
||||
<div class="mt-2 flex flex-wrap gap-3 text-xs text-muted">
|
||||
<span v-if="item.modified_at">修改时间:{{ item.modified_at }}</span>
|
||||
<span v-if="item.size_bytes">大小:{{ Math.max(1, Math.round(item.size_bytes / 1024)) }} KB</span>
|
||||
<span v-if="item.match_reason">匹配方式:{{ item.match_reason }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-default px-3 py-2 text-sm font-medium text-brand-600 transition hover:bg-brand-50"
|
||||
@click="emit('openPreview', item)"
|
||||
>
|
||||
<ExternalLink class="h-4 w-4" />
|
||||
查看履历
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -39,6 +39,7 @@ const props = defineProps<{
|
||||
isUploadingAttachments: boolean;
|
||||
canSendMessage: boolean;
|
||||
isShippingNoticeAgent: boolean;
|
||||
isMaintenanceAgent?: boolean;
|
||||
shippingSuggestedPrompt: string;
|
||||
shippingFocusTaskNo?: string;
|
||||
shippingFocusReason?: string;
|
||||
@@ -56,6 +57,8 @@ const emit = defineEmits<{
|
||||
'add-remote-url': [url: string];
|
||||
'shipping-inventory-selected': [event: Event];
|
||||
'use-shipping-suggested-prompt': [];
|
||||
'maintenance-ledger-config': [];
|
||||
'maintenance-create-record': [];
|
||||
'clear-shipping-focus': [];
|
||||
}>();
|
||||
|
||||
@@ -253,6 +256,27 @@ watch(
|
||||
<span>点发送开始处理</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isMaintenanceAgent"
|
||||
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('maintenance-create-record')"
|
||||
>
|
||||
{{ $t('maintenance.panel.recordTitle') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-brand-200 bg-brand-50 px-3 py-1 font-medium text-brand-700 transition-colors hover:bg-brand-100"
|
||||
@click="emit('maintenance-ledger-config')"
|
||||
>
|
||||
▦ {{ $t('maintenance.panel.ledgerTitle') }}
|
||||
</button>
|
||||
<span>{{ $t('maintenance.panel.adminOnly') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
|
||||
@@ -70,6 +70,20 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
|| (typeof msg.chat_log_id === 'number' ? `chat-log:${msg.chat_log_id}` : '')
|
||||
|| `${msg.role}:${msg.run_id || 'none'}:${String(msg.content || '').slice(0, 40)}:${index}`
|
||||
);
|
||||
|
||||
/**
|
||||
* 标记“当前消息后面是否还存在新的 assistant 消息”。
|
||||
* 核心逻辑:培训题卡属于“最新一张 assistant 题卡”才能继续交互;
|
||||
* 用户作答后虽然会追加一条 user 消息,但这不应让上一张题卡立刻失活。
|
||||
*/
|
||||
const isLatestAssistantMessage = (items: ChatMessage[], index: number) => {
|
||||
const current = items[index];
|
||||
if (!current || current.role !== 'assistant') return false;
|
||||
for (let i = items.length - 1; i > index; i -= 1) {
|
||||
if (items[i]?.role === 'assistant') return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -98,6 +112,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
|
||||
:show-chat-rating="showChatRating"
|
||||
:copied-index="copiedIndex"
|
||||
:is-shipping-notice-agent="isShippingNoticeAgent"
|
||||
:is-latest-assistant-message="isLatestAssistantMessage(messages, index)"
|
||||
:handlers="handlers"
|
||||
:leave-handlers="leaveHandlers"
|
||||
:shipping-handlers="shippingHandlers"
|
||||
|
||||
@@ -18,11 +18,29 @@ const props = defineProps<{
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
'change-page': [delta: number];
|
||||
'open-asset-history': [payload: { assetId: string; assetName: string }];
|
||||
}>();
|
||||
|
||||
const totalPages = computed(() =>
|
||||
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
|
||||
);
|
||||
const assetIdColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产编号'));
|
||||
const assetNameColumnIndex = computed(() => props.state.columns.findIndex((column) => column === '资产名称'));
|
||||
|
||||
function normalizeCellText(cell: unknown): string {
|
||||
return String(cell ?? '').trim();
|
||||
}
|
||||
|
||||
function canOpenAssetHistory(row: unknown[], cellIndex: number): boolean {
|
||||
return cellIndex === assetIdColumnIndex.value && !!normalizeCellText(row[cellIndex]);
|
||||
}
|
||||
|
||||
function emitAssetHistory(row: unknown[]): void {
|
||||
const assetId = normalizeCellText(row[assetIdColumnIndex.value]);
|
||||
const assetName = assetNameColumnIndex.value >= 0 ? normalizeCellText(row[assetNameColumnIndex.value]) : '';
|
||||
if (!assetId) return;
|
||||
emit('open-asset-history', { assetId, assetName });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -96,7 +114,15 @@ const totalPages = computed(() =>
|
||||
: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>
|
||||
<button
|
||||
v-if="canOpenAssetHistory(row, cellIndex)"
|
||||
type="button"
|
||||
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
|
||||
@click="emitAssetHistory(row)"
|
||||
>
|
||||
{{ cell ?? '-' }}
|
||||
</button>
|
||||
<div v-else class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Loader2 } from 'lucide-vue-next';
|
||||
import { Maximize2, Minimize2, 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';
|
||||
@@ -16,17 +16,63 @@ import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
|
||||
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
|
||||
import ShippingBatchWorkspaceDrawer from '@/features/chat/components/ShippingBatchWorkspaceDrawer.vue';
|
||||
import TrainingWorkspacePanel from '@/features/chat/components/TrainingWorkspacePanel.vue';
|
||||
import LedgerConfigPanel from '@/features/maintenance/components/LedgerConfigPanel.vue';
|
||||
import MaintenanceRecordManagerPanel from '@/features/maintenance/components/MaintenanceRecordManagerPanel.vue';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { matchesTrainingAgent } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
const page = useChatPageContext();
|
||||
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
|
||||
const isMaintenanceAgentPage = computed(() => {
|
||||
const name = String(page.currentAgent?.name || '').trim();
|
||||
return name === '设备维保助手' || (name.includes('设备维保') && name.includes('助手'));
|
||||
});
|
||||
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
|
||||
const isTrainingWorkspaceExpanded = ref(false);
|
||||
const maintenancePanel = ref<'ledger' | 'record' | null>(null);
|
||||
const maintenancePanelWidth = ref(560);
|
||||
const isMaintenancePanelFullscreen = ref(false);
|
||||
const isMaintenancePanelResizing = ref(false);
|
||||
const maintenancePanelStyle = computed(() => {
|
||||
if (isMaintenancePanelFullscreen.value) {
|
||||
return { width: '100%', minWidth: '100%', maxWidth: '100%' };
|
||||
}
|
||||
return {
|
||||
width: `${maintenancePanelWidth.value}px`,
|
||||
minWidth: '420px',
|
||||
maxWidth: '82vw',
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 开始拖拽设备维保右侧面板左边缘,允许管理员按表格内容临时调宽。
|
||||
* @param event - 鼠标按下事件。
|
||||
*/
|
||||
const startMaintenancePanelResize = (event: MouseEvent): void => {
|
||||
if (isMaintenancePanelFullscreen.value) return;
|
||||
event.preventDefault();
|
||||
isMaintenancePanelResizing.value = true;
|
||||
const startX = event.clientX;
|
||||
const startWidth = maintenancePanelWidth.value;
|
||||
const handleMove = (moveEvent: MouseEvent) => {
|
||||
const nextWidth = startWidth + (startX - moveEvent.clientX);
|
||||
const maxWidth = Math.max(420, Math.floor(window.innerWidth * 0.82));
|
||||
maintenancePanelWidth.value = Math.min(maxWidth, Math.max(420, nextWidth));
|
||||
};
|
||||
const stopResize = () => {
|
||||
isMaintenancePanelResizing.value = false;
|
||||
window.removeEventListener('mousemove', handleMove);
|
||||
window.removeEventListener('mouseup', stopResize);
|
||||
};
|
||||
window.addEventListener('mousemove', handleMove);
|
||||
window.addEventListener('mouseup', stopResize);
|
||||
};
|
||||
|
||||
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
|
||||
watch(() => page.currentAgentId, () => {
|
||||
isTrainingWorkspaceExpanded.value = false;
|
||||
maintenancePanel.value = null;
|
||||
isMaintenancePanelFullscreen.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -100,8 +146,11 @@ watch(() => page.currentAgentId, () => {
|
||||
<TrainingWorkspacePanel
|
||||
:current-agent="page.currentAgent"
|
||||
:current-user="page.currentUser"
|
||||
:agent-guides="page.agentGuides"
|
||||
:has-messages="page.messages.length > 0"
|
||||
:new-session-tick="page.viewId"
|
||||
:training="page.training"
|
||||
@open-guide="page.openGuideModal"
|
||||
@send-chat-prompt="page.handleSend($event)"
|
||||
@push-local-assistant-message="page.pushLocalAssistantMessage($event)"
|
||||
@update:expanded="isTrainingWorkspaceExpanded = $event"
|
||||
@@ -170,6 +219,7 @@ watch(() => page.currentAgentId, () => {
|
||||
:is-uploading-attachments="page.isUploadingAttachments"
|
||||
:can-send-message="page.canSendMessage"
|
||||
:is-shipping-notice-agent="page.isShippingNoticeAgent"
|
||||
:is-maintenance-agent="isMaintenanceAgentPage"
|
||||
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
|
||||
:shipping-focus-task-no="page.focusedShippingTaskNo"
|
||||
:shipping-focus-reason="page.shippingFocusReason"
|
||||
@@ -183,10 +233,63 @@ watch(() => page.currentAgentId, () => {
|
||||
@add-remote-url="page.addRemoteUrlAttachment"
|
||||
@shipping-inventory-selected="page.handleShippingInventorySelected"
|
||||
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
|
||||
@maintenance-ledger-config="maintenancePanel = 'ledger'"
|
||||
@maintenance-create-record="maintenancePanel = 'record'"
|
||||
@clear-shipping-focus="page.clearShippingFocus"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<aside
|
||||
v-if="isMaintenanceAgentPage && maintenancePanel"
|
||||
class="relative flex flex-col border-l border-default bg-surface shadow-[-8px_0_24px_rgba(15,23,42,0.06)]"
|
||||
:class="[
|
||||
isMaintenancePanelFullscreen ? 'absolute inset-y-0 right-0 z-30' : '',
|
||||
isMaintenancePanelResizing ? 'select-none' : '',
|
||||
]"
|
||||
:style="maintenancePanelStyle"
|
||||
>
|
||||
<button
|
||||
v-if="!isMaintenancePanelFullscreen"
|
||||
type="button"
|
||||
class="absolute inset-y-0 left-[-4px] z-10 w-2 cursor-col-resize bg-transparent hover:bg-brand-200/60"
|
||||
:title="$t('maintenance.panel.resizeTitle')"
|
||||
@mousedown="startMaintenancePanelResize"
|
||||
/>
|
||||
<div class="flex items-start justify-between gap-3 border-b border-default px-4 py-3">
|
||||
<div>
|
||||
<h2 class="text-base font-semibold text-primary">
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerTitle') : $t('maintenance.panel.recordTitle') }}
|
||||
</h2>
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
{{ maintenancePanel === 'ledger' ? $t('maintenance.panel.ledgerSubtitle') : $t('maintenance.panel.recordSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-secondary hover:bg-surface-soft"
|
||||
:title="isMaintenancePanelFullscreen ? $t('maintenance.panel.exitFullscreen') : $t('maintenance.panel.fullscreen')"
|
||||
@click="isMaintenancePanelFullscreen = !isMaintenancePanelFullscreen"
|
||||
>
|
||||
<Minimize2 v-if="isMaintenancePanelFullscreen" class="h-4 w-4" />
|
||||
<Maximize2 v-else class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-8 w-8 items-center justify-center rounded-lg border border-default text-sm text-secondary hover:bg-surface-soft"
|
||||
:title="$t('maintenance.panel.close')"
|
||||
@click="maintenancePanel = null"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-auto p-4">
|
||||
<LedgerConfigPanel v-if="maintenancePanel === 'ledger'" />
|
||||
<MaintenanceRecordManagerPanel v-else />
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<ChatBrowserPanel
|
||||
v-model:open="page.browserPanelOpen"
|
||||
v-model:draft-url="page.browserDraftUrl"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
/**
|
||||
* features/chat/components/ChatViewOverlays.vue
|
||||
* 对话页全局弹窗:文件预览、反馈、查询预览、请假 OA、删除确认、学习之窗。
|
||||
* 对话页全局弹窗与浮层:文件预览、反馈、查询预览、履历检索提示、请假 OA、删除确认、学习之窗。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
|
||||
@@ -10,6 +10,7 @@ import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewD
|
||||
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 { Loader2 } from 'lucide-vue-next';
|
||||
import { useChatPageContext } from '@/features/chat/composables/chat.context';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
@@ -45,7 +46,17 @@ function onFeedbackSubmitted() {
|
||||
:state="page.queryPreviewState"
|
||||
@close="page.queryPreview.close"
|
||||
@change-page="page.queryPreview.changePage"
|
||||
@open-asset-history="({ assetId, assetName }) => page.assetHistory.openHistory(assetId, assetName)"
|
||||
/>
|
||||
<div
|
||||
v-if="page.assetHistory.loading"
|
||||
class="pointer-events-none fixed inset-x-0 top-20 z-[145] flex justify-center px-4"
|
||||
>
|
||||
<div class="flex items-center gap-2 rounded-full border border-brand-200 bg-white/95 px-4 py-2 text-sm text-brand-700 shadow-lg backdrop-blur">
|
||||
<Loader2 class="h-4 w-4 animate-spin text-brand-500" />
|
||||
<span>正在搜索该资产的履历资料,请耐心等待...</span>
|
||||
</div>
|
||||
</div>
|
||||
<ChatLeaveAgentDialog
|
||||
v-model:open="page.showLeaveAgentDialog"
|
||||
v-model:keyword="page.leaveAgentKeyword"
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
BarChart3,
|
||||
BookOpen,
|
||||
CheckCircle2,
|
||||
ChevronDown,
|
||||
@@ -17,24 +16,26 @@ import {
|
||||
Download,
|
||||
PlayCircle,
|
||||
RefreshCcw,
|
||||
Send,
|
||||
ShieldCheck,
|
||||
Target,
|
||||
Users,
|
||||
XCircle,
|
||||
} from 'lucide-vue-next';
|
||||
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
currentAgent: Record<string, unknown> | null;
|
||||
currentUser: Record<string, unknown> | null;
|
||||
agentGuides: TrainingGuideLike[];
|
||||
hasMessages: boolean;
|
||||
newSessionTick: number;
|
||||
training: ShallowUnwrapRef<ReturnType<typeof useTrainingWorkspace>>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
'send-chat-prompt': [prompt: string];
|
||||
'push-local-assistant-message': [content: string];
|
||||
'open-guide': [guideId?: number];
|
||||
'update:expanded': [expanded: boolean];
|
||||
}>();
|
||||
|
||||
@@ -94,23 +95,25 @@ const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
|
||||
}
|
||||
};
|
||||
|
||||
const sendPrompt = (prompt: string) => {
|
||||
setWorkspaceExpanded(false);
|
||||
emit('send-chat-prompt', prompt);
|
||||
};
|
||||
|
||||
const currentAnswerLabel = computed(() => {
|
||||
const question = workspace.currentQuestion;
|
||||
if (!question) return '';
|
||||
return question.options?.find((item) => item.id === workspace.selectedOptionId)?.label || '';
|
||||
});
|
||||
|
||||
const trainingExamPdfGuide = computed(() => resolveTrainingExamPdfGuide(props.agentGuides));
|
||||
|
||||
// 默认进入 Chat 聊天页面(即收起工作区状态)
|
||||
const workspaceExpanded = ref(false);
|
||||
|
||||
const autoSyncInitialPrompt = () => {
|
||||
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
|
||||
emit('push-local-assistant-message', workspace.learnerChatPrompt);
|
||||
if (
|
||||
workspace.isTrainingAgent
|
||||
&& workspace.isHydrated
|
||||
&& !props.hasMessages
|
||||
&& workspace.shouldShowNewSessionReminder
|
||||
) {
|
||||
emit('push-local-assistant-message', workspace.newSessionReminderMessage);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -142,6 +145,14 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.newSessionTick,
|
||||
(tick, prevTick) => {
|
||||
if (!tick || tick === prevTick) return;
|
||||
autoSyncInitialPrompt();
|
||||
},
|
||||
);
|
||||
|
||||
const isCompactMode = computed(() => !workspaceExpanded.value);
|
||||
|
||||
const compactSummary = computed(() => {
|
||||
@@ -158,6 +169,14 @@ const compactSummary = computed(() => {
|
||||
}
|
||||
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
|
||||
});
|
||||
|
||||
const trainingTitle = computed(() => String(t('chat.training.title') || '').trim());
|
||||
const ruleItems = computed(() => ([
|
||||
t('chat.training.rules.rule1', { total: workspace.totalQuestionCount }),
|
||||
t('chat.training.rules.rule2'),
|
||||
t('chat.training.rules.rule3', { passScore: workspace.passScore }),
|
||||
t('chat.training.rules.rule4'),
|
||||
]));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -177,8 +196,8 @@ const compactSummary = computed(() => {
|
||||
<BookOpen class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.training.badge') }}
|
||||
</div>
|
||||
<div class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ $t('chat.training.title') }}
|
||||
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ trainingTitle }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1.5 flex flex-wrap gap-2">
|
||||
@@ -203,6 +222,15 @@ const compactSummary = computed(() => {
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4 shrink-0" />
|
||||
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.stage === 'video'"
|
||||
type="button"
|
||||
@@ -212,23 +240,6 @@ const compactSummary = computed(() => {
|
||||
<PlayCircle class="h-4 w-4" />
|
||||
{{ $t('chat.training.steps.video') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncLearnerToChat') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 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="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<BarChart3 class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncHrToChat') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@@ -276,8 +287,8 @@ const compactSummary = computed(() => {
|
||||
<BookOpen class="h-3.5 w-3.5" />
|
||||
{{ $t('chat.training.badge') }}
|
||||
</div>
|
||||
<div class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ $t('chat.training.title') }}
|
||||
<div v-if="trainingTitle" class="text-sm font-semibold text-primary md:text-base">
|
||||
{{ trainingTitle }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -304,21 +315,13 @@ const compactSummary = computed(() => {
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 items-center gap-2 rounded-xl border border-default bg-white px-3 py-2 text-xs font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
class="inline-flex h-9 items-center gap-2 rounded-xl border border-default bg-white px-3.5 text-xs font-medium leading-none text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncLearnerToChat') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="workspace.isAdminViewer"
|
||||
type="button"
|
||||
class="inline-flex min-h-9 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="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<BarChart3 class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.syncHrToChat') }}
|
||||
<BookOpen class="h-4 w-4 shrink-0" />
|
||||
<span class="leading-none">{{ $t('chat.training.actions.viewExamPdf') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -409,6 +412,15 @@ const compactSummary = computed(() => {
|
||||
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.video.title') }}</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</p>
|
||||
</div>
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.viewExamPdf') }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
|
||||
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
|
||||
@@ -427,14 +439,25 @@ const compactSummary = computed(() => {
|
||||
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.summary.title') }}</h3>
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.summary.description') }}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.startExam"
|
||||
>
|
||||
<Target class="h-4 w-4" />
|
||||
{{ $t('chat.training.summary.startExam') }}
|
||||
</button>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-if="trainingExamPdfGuide"
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="emit('open-guide', Number(trainingExamPdfGuide.id))"
|
||||
>
|
||||
<BookOpen class="h-4 w-4" />
|
||||
{{ $t('chat.training.actions.viewExamPdf') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.startExam"
|
||||
>
|
||||
<Target class="h-4 w-4" />
|
||||
{{ $t('chat.training.summary.startExam') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-3 md:grid-cols-2">
|
||||
@@ -475,7 +498,7 @@ const compactSummary = computed(() => {
|
||||
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
|
||||
{{ $t('chat.training.exam.passLine') }}
|
||||
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -565,7 +588,7 @@ const compactSummary = computed(() => {
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passTitle') : $t('chat.training.result.failTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-secondary">
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore: workspace.passScore }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -606,14 +629,6 @@ const compactSummary = computed(() => {
|
||||
<RefreshCcw class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.retryExam') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl border border-default bg-white px-4 py-2.5 text-sm font-medium text-secondary transition hover:bg-surface-soft"
|
||||
@click="sendPrompt(workspace.learnerChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.sendToChat') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -643,21 +658,9 @@ const compactSummary = computed(() => {
|
||||
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
|
||||
<ul class="mt-2 grid gap-1 text-xs leading-5 text-secondary">
|
||||
<li class="flex gap-2">
|
||||
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule1') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule2') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule3') }}</span>
|
||||
</li>
|
||||
<li class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ $t('chat.training.rules.rule4') }}</span>
|
||||
<span>{{ rule }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -667,32 +670,41 @@ const compactSummary = computed(() => {
|
||||
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
|
||||
<div class="grid gap-3 sm:grid-cols-2 xl:grid-cols-5">
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.total }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.total') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.total }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passed') }}</div>
|
||||
<div class="text-2xl font-semibold text-emerald-600">{{ workspace.stats.passed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.failed') }}</div>
|
||||
<div class="text-2xl font-semibold text-amber-600">{{ workspace.stats.failed }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.inProgress') }}</div>
|
||||
<div class="text-2xl font-semibold text-blue-600">{{ workspace.stats.inProgress }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-white p-3.5 shadow-sm">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="mt-1.5 text-xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
|
||||
<div class="flex items-center justify-center gap-2 text-center">
|
||||
<div class="text-sm text-muted">{{ $t('chat.training.hr.stats.passRate') }}</div>
|
||||
<div class="text-2xl font-semibold text-primary">{{ workspace.stats.passRate }}%</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="grid gap-3 xl:grid-cols-3">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.keywordLabel') }}</span>
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
|
||||
<label>
|
||||
<input
|
||||
v-model="workspace.hrKeyword"
|
||||
type="text"
|
||||
@@ -700,8 +712,7 @@ const compactSummary = computed(() => {
|
||||
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.statusLabel') }}</span>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrStatusFilter"
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
|
||||
@@ -712,8 +723,7 @@ const compactSummary = computed(() => {
|
||||
<option value="in_progress">{{ $t('chat.training.hr.status.in_progress') }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold uppercase tracking-[0.14em] text-muted">{{ $t('chat.training.hr.filters.departmentLabel') }}</span>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrDepartmentFilter"
|
||||
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
|
||||
@@ -724,17 +734,7 @@ const compactSummary = computed(() => {
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-10 items-center gap-2 rounded-xl border border-default bg-white px-4 text-xs font-medium text-secondary transition hover:bg-surface-soft sm:text-sm"
|
||||
@click="sendPrompt(workspace.managementChatPrompt)"
|
||||
>
|
||||
<Send class="h-4 w-4" />
|
||||
{{ $t('chat.training.hr.actions.askAgent') }}
|
||||
</button>
|
||||
<div class="flex justify-center xl:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex h-10 items-center gap-2 rounded-xl bg-brand-600 px-4 text-xs font-medium text-white transition hover:bg-brand-700 sm:text-sm"
|
||||
@@ -743,6 +743,7 @@ const compactSummary = computed(() => {
|
||||
<Download class="h-4 w-4" />
|
||||
{{ $t('chat.training.hr.actions.export') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
|
||||
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
|
||||
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
|
||||
@@ -21,6 +22,7 @@ import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload }
|
||||
export interface ChatMessageBubbleHandlers {
|
||||
renderMarkdown: (text: string) => string;
|
||||
onMarkdownClick: (event: MouseEvent) => void;
|
||||
openAssetHistory: (assetId: string, assetName?: string) => void;
|
||||
getInlineDownloadFiles: (text: string) => { cleanedText: string; files: InlineDownloadFile[] };
|
||||
downloadInlineFile: (file: InlineDownloadFile) => void;
|
||||
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
|
||||
@@ -47,6 +49,7 @@ const {
|
||||
showChatRating,
|
||||
copiedIndex,
|
||||
isShippingNoticeAgent,
|
||||
isLatestAssistantMessage,
|
||||
handlers,
|
||||
leaveHandlers,
|
||||
shippingHandlers,
|
||||
@@ -58,6 +61,7 @@ const {
|
||||
showChatRating: boolean;
|
||||
copiedIndex: number | null;
|
||||
isShippingNoticeAgent: boolean;
|
||||
isLatestAssistantMessage: boolean;
|
||||
handlers: ChatMessageBubbleHandlers;
|
||||
leaveHandlers: LeaveMessageHandlers;
|
||||
shippingHandlers: ShippingMappingHandlers;
|
||||
@@ -91,20 +95,35 @@ const isTrainingVideoMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
// 只要包含特定引导文案,就显示视频占位符,不限于最后一条消息
|
||||
const content = message.content || '';
|
||||
return content.includes('专属入职培训助手') || (content.includes('看视频') && content.includes('已看完'));
|
||||
return content.includes('专属入职培训助手')
|
||||
|| content.includes('onboarding training assistant')
|
||||
|| content.includes('ผู้ช่วยอบรมพนักงานใหม่')
|
||||
|| content.includes('入职培训视频')
|
||||
|| content.includes('training video');
|
||||
});
|
||||
|
||||
const isTrainingSummaryMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
const content = message.content || '';
|
||||
return content.includes('完成视频学习') || content.includes('复盘重点知识') || content.includes('复盘知识点') || content.includes('总结重点知识');
|
||||
return content.includes('完成视频学习')
|
||||
|| content.includes('复盘重点知识')
|
||||
|| content.includes('复盘知识点')
|
||||
|| content.includes('总结重点知识')
|
||||
|| content.includes('核心知识点')
|
||||
|| content.includes('key knowledge points')
|
||||
|| content.includes('ประเด็นสำคัญ');
|
||||
});
|
||||
|
||||
const isTrainingResultMessage = computed(() => {
|
||||
if (message.role !== 'assistant') return false;
|
||||
// 只要是结果文案,就显示结算卡片,不限于最后一条消息
|
||||
const content = message.content || '';
|
||||
return content.includes('考试结束') || content.includes('顺利通过新人考核');
|
||||
return content.includes('考试结束')
|
||||
|| content.includes('顺利通过新人考核')
|
||||
|| content.includes('Exam finished')
|
||||
|| content.includes('passed the onboarding assessment')
|
||||
|| content.includes('สอบเสร็จแล้ว')
|
||||
|| content.includes('ผ่านการประเมินพนักงานใหม่');
|
||||
});
|
||||
|
||||
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
|
||||
@@ -123,7 +142,7 @@ const showShippingActionsPanel = computed(() =>
|
||||
&& !!message.shipping_actions?.length
|
||||
&& message.type !== 'shipping-match-result',
|
||||
);
|
||||
const isLastMessage = computed(() => index === messageCount - 1);
|
||||
const isLastMessage = computed(() => index === messageCount - 1 || (message.role === 'assistant' && isLatestAssistantMessage));
|
||||
const isCopied = computed(() => copiedIndex === index);
|
||||
const renderedMarkdown = computed(() => (
|
||||
message.role === 'assistant' ? handlers.renderMarkdown(message.content) : ''
|
||||
@@ -431,10 +450,11 @@ const inlineDialogPage = ref(1);
|
||||
const activeInlineFilterIndexes = computed(() => {
|
||||
const table = activeInlineDialogEntry.value?.table;
|
||||
if (!table) {
|
||||
return { assetId: -1, custodianPerson: -1, custodianDept: -1 };
|
||||
return { assetId: -1, assetName: -1, custodianPerson: -1, custodianDept: -1 };
|
||||
}
|
||||
return {
|
||||
assetId: findInlineTableHeaderIndex(table.rawHeaders, ['asset_id', 'asset_no']),
|
||||
assetName: findInlineTableHeaderIndex(table.rawHeaders, ['asset_name']),
|
||||
custodianPerson: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_person', 'custodian_name']),
|
||||
custodianDept: findInlineTableHeaderIndex(table.rawHeaders, ['custodian_dept', 'department_name']),
|
||||
};
|
||||
@@ -521,6 +541,19 @@ function changeInlineDialogPage(nextPage: number): void {
|
||||
inlineDialogPage.value = Math.min(Math.max(1, nextPage), activeInlineTotalPages.value);
|
||||
}
|
||||
|
||||
function canOpenInlineAssetHistory(cellIndex: number, cellValue: string): boolean {
|
||||
const normalizedValue = String(cellValue || '').trim();
|
||||
return cellIndex === activeInlineFilterIndexes.value.assetId && !!normalizedValue && normalizedValue !== '-';
|
||||
}
|
||||
|
||||
function openInlineAssetHistory(row: string[]): void {
|
||||
const indexes = activeInlineFilterIndexes.value;
|
||||
const assetId = indexes.assetId >= 0 ? String(row[indexes.assetId] || '').trim() : '';
|
||||
const assetName = indexes.assetName >= 0 ? String(row[indexes.assetName] || '').trim() : '';
|
||||
if (!assetId || assetId === '-') return;
|
||||
handlers.openAssetHistory(assetId, assetName === '-' ? '' : assetName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应聊天消息里的内嵌文件下载按钮点击。
|
||||
* 核心逻辑:复用页面层 handlers 生成 Blob 下载,组件层只负责把当前文件对象回传出去。
|
||||
@@ -588,25 +621,32 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:action-button-class="handlers.shippingActionButtonClass"
|
||||
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
|
||||
/>
|
||||
<MaintenanceDeviceResultCard
|
||||
v-else-if="message.type === 'maintenance-device-result'"
|
||||
:message="message"
|
||||
/>
|
||||
<TrainingExamQuestionMessage
|
||||
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
|
||||
:question="trainingHandlers.getQuestion()!"
|
||||
:current-question-index="trainingHandlers.getCurrentQuestionIndex()"
|
||||
:answered-count="trainingHandlers.getAnsweredCount()"
|
||||
:total-count="trainingHandlers.getTotalCount()"
|
||||
:pass-score="trainingHandlers.getPassScore()"
|
||||
:score="trainingHandlers.getScore()"
|
||||
:selected-option-id="trainingHandlers.getSelectedOptionId()"
|
||||
:answer-locked="trainingHandlers.getAnswerLocked()"
|
||||
:feedback-correct="trainingHandlers.getFeedbackCorrect()"
|
||||
:answer-label="trainingHandlers.getAnswerLabel()"
|
||||
:latest-exam-feedback="trainingHandlers.getLatestExamFeedback()"
|
||||
:is-thinking="isThinking"
|
||||
@select="trainingHandlers.onSelect"
|
||||
@next="trainingHandlers.onNext"
|
||||
/>
|
||||
<TrainingResultCard
|
||||
v-else-if="isTrainingResultMessage"
|
||||
:score="trainingHandlers.getScore()"
|
||||
:is-passed="trainingHandlers.getScore() >= 90"
|
||||
:score="trainingHandlers.getResultScore()"
|
||||
:is-passed="trainingHandlers.getResultPassed()"
|
||||
:pass-score="trainingHandlers.getPassScore()"
|
||||
:correct-count="trainingHandlers.getCorrectCount()"
|
||||
:wrong-count="trainingHandlers.getWrongCount()"
|
||||
:is-thinking="isThinking"
|
||||
@@ -617,6 +657,7 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
v-else-if="renderedMarkdown"
|
||||
ref="markdownContainer"
|
||||
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
|
||||
@click="handlers.onMarkdownClick"
|
||||
v-html="renderedMarkdown"
|
||||
/>
|
||||
|
||||
@@ -885,7 +926,15 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
:key="`${activeInlineDialogEntry.file.name}-dialog-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>
|
||||
<button
|
||||
v-if="canOpenInlineAssetHistory(cellIndex, cell)"
|
||||
type="button"
|
||||
class="whitespace-pre-wrap break-all text-left font-medium text-brand-600 underline-offset-2 transition hover:underline"
|
||||
@click="openInlineAssetHistory(row)"
|
||||
>
|
||||
{{ cell || '-' }}
|
||||
</button>
|
||||
<div v-else class="whitespace-pre-wrap break-all">{{ cell || '-' }}</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* features/chat/components/messages/MaintenanceDeviceResultCard.vue
|
||||
* 用途:设备维保助手会话中的设备台账查询结果卡片。
|
||||
* 依赖:chat.types、ledger/record 类型、vue-i18n。
|
||||
* 逻辑:后端返回 maintenance-device-result payload 后,本组件按原型展示设备基础信息、匹配状态和快捷操作。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ChatMessage } from '../../types/chat.types';
|
||||
import type { MaintenanceDevice } from '@/features/maintenance/types/ledger.types';
|
||||
import type { MaintenanceRecord } from '@/features/maintenance/types/record.types';
|
||||
|
||||
interface MaintenanceDeviceResultPayload {
|
||||
matched?: boolean;
|
||||
device?: MaintenanceDevice;
|
||||
records?: MaintenanceRecord[];
|
||||
actions?: Array<{ id: string; label: string }>;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
message: ChatMessage;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const payload = computed<MaintenanceDeviceResultPayload | null>(() => {
|
||||
const raw = props.message.payload;
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return raw as MaintenanceDeviceResultPayload;
|
||||
});
|
||||
|
||||
const device = computed(() => payload.value?.device || null);
|
||||
const records = computed(() => payload.value?.records || []);
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
const status = device.value?.deviceStatus;
|
||||
if (status === 'in_use') return t('maintenance.ledger.status.inUse');
|
||||
if (status === 'disabled') return t('maintenance.ledger.status.disabled');
|
||||
if (status === 'scrapped') return t('maintenance.ledger.status.scrapped');
|
||||
if (status === 'sold') return t('maintenance.ledger.status.sold');
|
||||
return status || '-';
|
||||
});
|
||||
|
||||
const rows = computed(() => {
|
||||
const item = device.value;
|
||||
if (!item) return [];
|
||||
return [
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.deviceCode'), value: item.deviceCode },
|
||||
{ label: t('maintenance.ledger.fields.deviceName'), value: item.deviceName },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.modelSpec'), value: item.modelSpec },
|
||||
{ label: t('maintenance.ledger.fields.department'), value: item.department },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.devicePosition'), value: item.installLocation },
|
||||
{ label: t('maintenance.ledger.fields.deviceStatus'), value: statusLabel.value },
|
||||
],
|
||||
[
|
||||
{ label: t('maintenance.ledger.fields.manufacturer'), value: item.manufacturer },
|
||||
{ label: t('maintenance.ledger.fields.startDate'), value: item.startDate },
|
||||
],
|
||||
];
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section v-if="device" class="mt-3 rounded-xl border border-slate-300 bg-white p-3 text-sm text-slate-800 shadow-sm">
|
||||
<div class="flex items-center justify-between gap-3 rounded-t-lg border border-slate-200 bg-slate-50 px-3 py-2">
|
||||
<h3 class="font-semibold">{{ t('maintenance.chat.deviceLedgerInfo') }}</h3>
|
||||
<span class="rounded-full bg-emerald-50 px-2.5 py-0.5 text-xs font-semibold text-emerald-700">
|
||||
{{ t('maintenance.chat.matched') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="overflow-hidden border-x border-b border-slate-200">
|
||||
<table class="w-full table-fixed text-sm">
|
||||
<tbody>
|
||||
<tr v-for="(row, rowIndex) in rows" :key="rowIndex" class="border-t border-slate-200 first:border-t-0">
|
||||
<template v-for="cell in row" :key="cell.label">
|
||||
<th class="w-[16%] bg-slate-100 px-3 py-2 text-left font-semibold text-slate-700">{{ cell.label }}</th>
|
||||
<td class="w-[34%] px-3 py-2 text-slate-800">{{ cell.value || '-' }}</td>
|
||||
</template>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div v-if="records.length" class="mt-3 overflow-hidden rounded-lg border border-slate-200">
|
||||
<div class="bg-slate-50 px-3 py-2 text-xs font-semibold text-slate-600">
|
||||
{{ t('maintenance.chat.recentRecords', { count: records.length }) }}
|
||||
</div>
|
||||
<table class="w-full text-left text-xs">
|
||||
<thead class="bg-slate-50 text-slate-500">
|
||||
<tr>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.reportDate') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.faultDescription') }}</th>
|
||||
<th class="px-3 py-2">{{ t('maintenance.record.fields.repairer') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="record in records.slice(0, 3)" :key="record.id" class="border-t border-slate-200">
|
||||
<td class="px-3 py-2">{{ record.reportDate || '-' }}</td>
|
||||
<td class="max-w-[260px] truncate px-3 py-2">{{ record.faultDescription || '-' }}</td>
|
||||
<td class="px-3 py-2">{{ record.repairer || '-' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" class="rounded-lg bg-brand-600 px-3 py-2 text-xs font-semibold text-white">
|
||||
{{ t('maintenance.chat.viewRepairHistory') }}
|
||||
</button>
|
||||
<button type="button" class="rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs font-semibold text-slate-700">
|
||||
{{ t('maintenance.chat.addRepairRecord') }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -5,23 +5,27 @@
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { CheckCircle2, XCircle, ClipboardCheck } from 'lucide-vue-next';
|
||||
import type { TrainingQuestion } from '@/features/chat/training/training.types';
|
||||
import type { TrainingExamTransitionFeedback, TrainingQuestion } from '@/features/chat/training/training.types';
|
||||
|
||||
export interface TrainingHandlers {
|
||||
getQuestion: () => TrainingQuestion | null;
|
||||
getCurrentQuestionIndex: () => number;
|
||||
getAnsweredCount: () => number;
|
||||
getTotalCount: () => number;
|
||||
getPassScore: () => number;
|
||||
getScore: () => number;
|
||||
getSelectedOptionId: () => string;
|
||||
getAnswerLocked: () => boolean;
|
||||
getFeedbackCorrect: () => boolean;
|
||||
getAnswerLabel: () => string;
|
||||
getLatestExamFeedback: () => TrainingExamTransitionFeedback | null;
|
||||
onSelect: (optionId: string) => void;
|
||||
onNext: () => void;
|
||||
onPlayVideo: () => void;
|
||||
onStartExam: () => void;
|
||||
onRestartExam: () => void;
|
||||
getResultScore: () => number;
|
||||
getResultPassed: () => boolean;
|
||||
getCorrectCount: () => number;
|
||||
getWrongCount: () => number;
|
||||
getSummaryPoints: () => string[];
|
||||
@@ -33,11 +37,13 @@ const props = defineProps<{
|
||||
currentQuestionIndex: number;
|
||||
answeredCount: number;
|
||||
totalCount: number;
|
||||
passScore: number;
|
||||
score: number;
|
||||
selectedOptionId: string;
|
||||
answerLocked: boolean;
|
||||
feedbackCorrect: boolean;
|
||||
answerLabel: string;
|
||||
latestExamFeedback: TrainingExamTransitionFeedback | null;
|
||||
isThinking: boolean;
|
||||
}>();
|
||||
|
||||
@@ -46,7 +52,6 @@ const emit = defineEmits<{
|
||||
next: [];
|
||||
}>();
|
||||
|
||||
const passLine = 90;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -68,7 +73,42 @@ const passLine = 90;
|
||||
</div>
|
||||
<div class="rounded-lg bg-slate-50 px-3 py-1.5 font-medium text-slate-600 border border-slate-100 flex items-center gap-2">
|
||||
<span>及格线:</span>
|
||||
<span class="text-slate-800 font-bold">{{ passLine }} 分</span>
|
||||
<span class="text-slate-800 font-bold">{{ passScore }} 分</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 上一题反馈摘要:自动推进到下一题后,仍需把对错、解析和分数留在同一张题卡顶部 -->
|
||||
<div
|
||||
v-if="latestExamFeedback"
|
||||
class="rounded-2xl border p-4"
|
||||
:class="latestExamFeedback.correct ? 'border-emerald-100 bg-emerald-50/60' : 'border-red-100 bg-red-50/60'"
|
||||
>
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex items-center gap-2 text-sm font-bold" :class="latestExamFeedback.correct ? 'text-emerald-700' : 'text-red-700'">
|
||||
<CheckCircle2 v-if="latestExamFeedback.correct" class="h-4 w-4" />
|
||||
<XCircle v-else class="h-4 w-4" />
|
||||
{{ latestExamFeedback.correct ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
|
||||
</div>
|
||||
<div class="rounded-lg bg-white/70 px-3 py-1 text-xs font-semibold text-slate-600">
|
||||
{{ $t('chat.training.exam.currentScore', { score: latestExamFeedback.scoreAfterAnswer }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 space-y-2 text-[13px] leading-6 text-slate-600">
|
||||
<div class="text-slate-500">{{ latestExamFeedback.questionPrompt }}</div>
|
||||
<div class="flex gap-2">
|
||||
<span class="font-medium" :class="latestExamFeedback.correct ? 'text-emerald-600' : 'text-red-600'">
|
||||
{{ $t('chat.training.exam.selectedAnswer', { answer: latestExamFeedback.selectedAnswerLabel || '--' }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="!latestExamFeedback.correct" class="flex gap-2">
|
||||
<span class="text-emerald-600 font-medium">
|
||||
{{ $t('chat.training.exam.correctAnswer', { answer: latestExamFeedback.correctAnswerLabel || '--' }) }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="pl-2 border-l-2 border-slate-200/60 text-slate-500/90">
|
||||
{{ latestExamFeedback.explanation }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ShieldCheck, XCircle, RotateCcw, CheckCircle2 } from 'lucide-vue-next';
|
||||
defineProps<{
|
||||
score: number;
|
||||
isPassed: boolean;
|
||||
passScore: number;
|
||||
correctCount: number;
|
||||
wrongCount: number;
|
||||
isThinking: boolean;
|
||||
@@ -65,7 +66,7 @@ const emit = defineEmits<{
|
||||
|
||||
<!-- 描述语 -->
|
||||
<div class="text-sm leading-relaxed text-slate-600">
|
||||
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
|
||||
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore }) }}
|
||||
</div>
|
||||
|
||||
<!-- 操作 -->
|
||||
|
||||
@@ -650,6 +650,7 @@ export function useChat() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* features/chat/composables/useChatAssetHistory.ts
|
||||
* 用途:管理固定资产履历检索、友好提示与文件预览跳转。
|
||||
* 依赖:chat.api、useChatSourceFiles 暴露的 openPreview、聊天提示消息。
|
||||
* 逻辑:页面层统一持有“打开履历”动作,消息气泡/查询预览弹窗复用该入口;
|
||||
* 点击资产编号后先进入“检索中”状态,命中履历文件则直接打开最佳候选预览,未命中时仅提示用户。
|
||||
*/
|
||||
import { ref } from 'vue';
|
||||
import { searchAssetHistoryFiles } from '../api/chat.api';
|
||||
import type { AssetHistoryFileItem, SourceFileLink } from '../types/chat.types';
|
||||
import type { ComputedRef } from 'vue';
|
||||
|
||||
interface UseChatAssetHistoryOptions {
|
||||
agentId: ComputedRef<number>;
|
||||
openPreview: (file: SourceFileLink) => Promise<void>;
|
||||
warn: (message: string) => void;
|
||||
}
|
||||
|
||||
export function useChatAssetHistory(options: UseChatAssetHistoryOptions) {
|
||||
const open = ref(false);
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const assetId = ref('');
|
||||
const assetName = ref('');
|
||||
const items = ref<AssetHistoryFileItem[]>([]);
|
||||
|
||||
const close = () => {
|
||||
open.value = false;
|
||||
loading.value = false;
|
||||
error.value = '';
|
||||
items.value = [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 检索资产履历并直接打开最佳预览结果。
|
||||
* AI 触发时机:当用户点击聊天表格中的“资产编号”,希望直接查看该资产履历时调用。
|
||||
* 核心逻辑:点击后先切入“检索中”状态,再按“资产编号 + 资产名称”查询共享盘候选文件,命中后默认取排序最优的第一条直接预览;
|
||||
* 未命中或查询失败时,仅给用户展示友好提示,不再弹出中间候选列表。
|
||||
* 参数约束:至少要提供资产编号或资产名称之一;候选文件排序由后端负责,本方法默认信任第一条结果。
|
||||
*/
|
||||
const openHistory = async (nextAssetId: string, nextAssetName = '') => {
|
||||
const normalizedAssetId = String(nextAssetId || '').trim();
|
||||
const normalizedAssetName = String(nextAssetName || '').trim();
|
||||
if (loading.value) {
|
||||
return;
|
||||
}
|
||||
if (!normalizedAssetId && !normalizedAssetName) {
|
||||
options.warn('当前资产缺少可用于检索履历的编号或名称');
|
||||
return;
|
||||
}
|
||||
|
||||
assetId.value = normalizedAssetId;
|
||||
assetName.value = normalizedAssetName;
|
||||
open.value = false;
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
items.value = [];
|
||||
try {
|
||||
const result = await searchAssetHistoryFiles(options.agentId.value, {
|
||||
asset_id: normalizedAssetId,
|
||||
asset_name: normalizedAssetName,
|
||||
});
|
||||
items.value = Array.isArray(result?.items) ? result.items : [];
|
||||
const bestMatch = items.value[0];
|
||||
if (!bestMatch) {
|
||||
const displayName = normalizedAssetId || normalizedAssetName;
|
||||
options.warn(`未找到资产 ${displayName} 的履历文件,如确认应有履历,请联系管理员补充。`);
|
||||
return;
|
||||
}
|
||||
await openHistoryFilePreview(bestMatch);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '检索资产履历失败';
|
||||
error.value = message;
|
||||
options.warn(`履历查询失败:${message}`);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 打开履历文件预览。
|
||||
* AI 触发时机:当用户在“资产履历”列表里点击某一条“查看履历”时调用。
|
||||
* 核心逻辑:先关闭履历候选列表弹窗,避免与文件预览弹窗叠层冲突,再交给聊天页通用预览器处理。
|
||||
* 参数约束:必须传入带有 name/url 的有效履历文件项,url 必须是后端允许代理的共享盘路径。
|
||||
*/
|
||||
const openHistoryFilePreview = async (item: AssetHistoryFileItem) => {
|
||||
close();
|
||||
await options.openPreview({
|
||||
name: item.name,
|
||||
url: item.url,
|
||||
actualExt: item.actual_ext,
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
open,
|
||||
loading,
|
||||
error,
|
||||
assetId,
|
||||
assetName,
|
||||
items,
|
||||
close,
|
||||
openHistory,
|
||||
openHistoryFilePreview,
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,7 @@ export interface AgentGuide {
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type?: string;
|
||||
guide_usage?: string;
|
||||
file_url?: string;
|
||||
file_path?: string;
|
||||
remark?: string;
|
||||
@@ -42,8 +43,9 @@ export function useChatGuides(options: UseChatGuidesOptions) {
|
||||
guides.value = [];
|
||||
};
|
||||
|
||||
const openModal = () => {
|
||||
const first = guides.value[0];
|
||||
const openModal = (guideId?: number | null) => {
|
||||
const preferred = guideId ? guides.value.find((g) => g.id === guideId) : null;
|
||||
const first = preferred || guides.value[0];
|
||||
if (!first) return;
|
||||
activeGuideId.value = first.id;
|
||||
showModal.value = true;
|
||||
|
||||
@@ -25,8 +25,10 @@ import { useChatScroll } from './useChatScroll';
|
||||
import { useChatSessions } from './useChatSessions';
|
||||
import { useChatShipping } from './useChatShipping';
|
||||
import { useChatSourceFiles } from './useChatSourceFiles';
|
||||
import { useChatAssetHistory } from './useChatAssetHistory';
|
||||
import { useChatStore } from '../stores/chat.store';
|
||||
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
|
||||
import { useTrainingWorkspace } from './useTrainingWorkspace';
|
||||
import { matchesTrainingAgent } from '../training/trainingWorkspace.utils';
|
||||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||||
import {
|
||||
createChatPageConversationApi,
|
||||
@@ -106,6 +108,7 @@ export function useChatPage() {
|
||||
messages,
|
||||
isThinking,
|
||||
conversationId,
|
||||
viewId,
|
||||
runs,
|
||||
activeRunId,
|
||||
activateRun,
|
||||
@@ -164,6 +167,11 @@ export function useChatPage() {
|
||||
openPreview,
|
||||
parsePlmPreviewLink,
|
||||
} = sourceFiles;
|
||||
const assetHistory = useChatAssetHistory({
|
||||
agentId: currentAgentId,
|
||||
openPreview,
|
||||
warn: (text) => msg.warning(text),
|
||||
});
|
||||
|
||||
watch(currentAgentId, (id) => {
|
||||
chatStore.setCurrentAgentId(id > 0 ? id : null);
|
||||
@@ -342,6 +350,7 @@ export function useChatPage() {
|
||||
const training = useTrainingWorkspace({
|
||||
currentAgent: computed(() => agent.currentAgent.value),
|
||||
currentUser: computed(() => currentUser.value),
|
||||
currentGuides: computed(() => chatGuides.guides.value),
|
||||
pushLocalAssistantMessage,
|
||||
pushLocalUserMessage,
|
||||
});
|
||||
@@ -353,6 +362,7 @@ export function useChatPage() {
|
||||
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
|
||||
parsePlmPreviewLink,
|
||||
openPreview,
|
||||
openAssetHistory: assetHistory.openHistory,
|
||||
getMessageLinks,
|
||||
getDisplayRetrieverResources,
|
||||
getSourceLinks,
|
||||
@@ -479,6 +489,7 @@ export function useChatPage() {
|
||||
isThinking,
|
||||
shippingActionBusy,
|
||||
conversationId,
|
||||
viewId,
|
||||
input,
|
||||
browser,
|
||||
queryPreview,
|
||||
@@ -492,6 +503,7 @@ export function useChatPage() {
|
||||
queryPreviewLoading: queryPreview.loading,
|
||||
queryPreviewError: queryPreview.error,
|
||||
queryPreviewState: queryPreview.state,
|
||||
assetHistory,
|
||||
...agent,
|
||||
agentGuides: chatGuides.guides,
|
||||
showGuideModal: chatGuides.showModal,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingProgress,
|
||||
@@ -15,6 +17,8 @@ import {
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
TrainingAnswerRecord,
|
||||
TrainingContentConfig,
|
||||
TrainingExamTransitionFeedback,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingProgressRecord,
|
||||
@@ -24,6 +28,13 @@ import type {
|
||||
TrainingStats,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
matchesTrainingAgent,
|
||||
resolveTrainingContentConfig,
|
||||
resolveTrainingVideoGuide,
|
||||
resolveTrainingVideoUrl,
|
||||
type TrainingGuideLike,
|
||||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
@@ -36,44 +47,41 @@ type TrainingUserLike = {
|
||||
real_name?: string | null;
|
||||
employee_id?: string | null;
|
||||
department?: string | null;
|
||||
feature_permissions?: {
|
||||
training_hr_manage?: boolean;
|
||||
} | null;
|
||||
} | null | undefined;
|
||||
|
||||
export interface UseTrainingWorkspaceOptions {
|
||||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||||
currentUser: ComputedRef<TrainingUserLike>;
|
||||
currentGuides: ComputedRef<TrainingGuideLike[]>;
|
||||
pushLocalAssistantMessage?: (content: string) => Promise<void>;
|
||||
pushLocalUserMessage?: (content: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||||
* AI 触发时机:当需要把培训 UI 只挂在指定 Agent 上时使用,优先读 extra_config 显式开关,避免误伤其他聊天场景。
|
||||
*/
|
||||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
const explicitFlags = [
|
||||
extraConfig.training_workspace_enabled,
|
||||
extraConfig.training_mode,
|
||||
extraConfig.training_agent,
|
||||
];
|
||||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||||
return true;
|
||||
}
|
||||
const name = String(agent?.name || '').trim();
|
||||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||||
}
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
|
||||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
/**
|
||||
* 按百分制计算当前答题得分。
|
||||
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
|
||||
*/
|
||||
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
|
||||
if (totalQuestionCount <= 0) return 0;
|
||||
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
|
||||
};
|
||||
|
||||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { currentAgent, currentUser, currentGuides, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { t, tm } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
@@ -83,10 +91,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const selectedOptionId = ref('');
|
||||
const answerLocked = ref(false);
|
||||
const currentFeedbackCorrect = ref(false);
|
||||
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
|
||||
const latestSettledResult = ref<{
|
||||
score: number;
|
||||
correctCount: number;
|
||||
wrongCount: number;
|
||||
isPassed: boolean;
|
||||
} | null>(null);
|
||||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||||
const completionDate = ref<string | null>(null);
|
||||
const currentJoinDate = ref<string | null>(null);
|
||||
const isHydrated = ref(false);
|
||||
const hasWarnedPersistFailure = ref(false);
|
||||
const hasWarnedLoadFailure = ref(false);
|
||||
|
||||
const hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
@@ -110,12 +127,12 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
const summaryPoints = computed(() => {
|
||||
const defaultSummaryPoints = computed(() => {
|
||||
const raw = tm('chat.training.summaryPoints');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
|
||||
const summaryChecklist = computed(() => {
|
||||
const defaultSummaryChecklist = computed(() => {
|
||||
const raw = tm('chat.training.summaryChecklist');
|
||||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||||
});
|
||||
@@ -134,7 +151,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}));
|
||||
});
|
||||
|
||||
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
|
||||
const mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.map((item) => {
|
||||
const type = String(item.type || 'single') as TrainingQuestion['type'];
|
||||
const rawOptions = Array.isArray(item.options) ? item.options : [];
|
||||
const options = type === 'boolean'
|
||||
@@ -152,14 +169,32 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
explanation: String(item.explanation || ''),
|
||||
options,
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
const defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
|
||||
|
||||
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
|
||||
currentAgent.value,
|
||||
{
|
||||
passScore: DEFAULT_PASS_SCORE,
|
||||
summaryPoints: defaultSummaryPoints.value,
|
||||
summaryChecklist: defaultSummaryChecklist.value,
|
||||
questionBank: defaultQuestionBank.value,
|
||||
},
|
||||
booleanOptions.value,
|
||||
));
|
||||
|
||||
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
|
||||
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
|
||||
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
|
||||
const passScore = computed(() => trainingContent.value.passScore);
|
||||
|
||||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||||
const answeredCount = computed(() => answerRecords.value.length);
|
||||
const correctCount = computed(() => answerRecords.value.filter((item) => item.correct).length);
|
||||
const wrongCount = computed(() => answerRecords.value.filter((item) => !item.correct).length);
|
||||
const isPassed = computed(() => score.value >= 90);
|
||||
const isPassed = computed(() => score.value >= passScore.value);
|
||||
|
||||
const learnerProgressPercent = computed(() => {
|
||||
if (stage.value === 'video') return 25;
|
||||
@@ -191,10 +226,67 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
answerRecords.value = [];
|
||||
completionDate.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
|
||||
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
|
||||
*/
|
||||
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
|
||||
if (!question) return optionId;
|
||||
return question.options?.find((item) => item.id === optionId)?.label || optionId;
|
||||
};
|
||||
|
||||
/**
|
||||
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
|
||||
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
|
||||
*/
|
||||
const buildExamFeedback = (
|
||||
question: TrainingQuestion | null,
|
||||
answerRecord: TrainingAnswerRecord | null | undefined,
|
||||
scoreAfterAnswer: number,
|
||||
): TrainingExamTransitionFeedback | null => {
|
||||
if (!question || !answerRecord) return null;
|
||||
return {
|
||||
questionId: question.id,
|
||||
questionPrompt: question.prompt,
|
||||
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
|
||||
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
|
||||
explanation: question.explanation,
|
||||
correct: Boolean(answerRecord.correct),
|
||||
scoreAfterAnswer,
|
||||
};
|
||||
};
|
||||
|
||||
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
|
||||
question?.type === 'boolean'
|
||||
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
|
||||
: t('chat.training.chatPrompts.assistantQuestionSingleType')
|
||||
);
|
||||
|
||||
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
|
||||
if (!question) return '';
|
||||
const optionLines = (question.options || []).map((option) => option.label).join('\n');
|
||||
return [
|
||||
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
|
||||
optionLines,
|
||||
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
|
||||
].filter(Boolean).join('\n');
|
||||
};
|
||||
|
||||
const buildSummaryAssistantMessage = () => {
|
||||
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
|
||||
return [
|
||||
t('chat.training.chatPrompts.assistantSummaryIntro'),
|
||||
summaryLines,
|
||||
'',
|
||||
t('chat.training.chatPrompts.assistantSummaryReady'),
|
||||
].join('\n');
|
||||
};
|
||||
|
||||
const syncAnswerStateForCurrentQuestion = () => {
|
||||
const questionId = currentQuestion.value?.id;
|
||||
const currentAnswer = questionId
|
||||
@@ -210,6 +302,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
currentJoinDate.value = null;
|
||||
latestSettledResult.value = null;
|
||||
return;
|
||||
}
|
||||
stage.value = record.stage;
|
||||
@@ -219,6 +312,22 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
|
||||
completionDate.value = record.completionDate;
|
||||
currentJoinDate.value = record.joinDate || null;
|
||||
latestExamFeedback.value = null;
|
||||
if (record.stage === 'result') {
|
||||
latestSettledResult.value = {
|
||||
score: Number(record.score || 0),
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
|
||||
};
|
||||
}
|
||||
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
|
||||
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
|
||||
const previousAnswer = previousQuestion
|
||||
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
|
||||
: null;
|
||||
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
|
||||
}
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
@@ -237,13 +346,23 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||||
try {
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||||
hasWarnedPersistFailure.value = false;
|
||||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||||
completionDate.value = saved.completionDate;
|
||||
if (isAdminViewer.value) {
|
||||
void loadAdminRecords();
|
||||
}
|
||||
} catch {
|
||||
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
|
||||
} catch (error) {
|
||||
if (!hasWarnedPersistFailure.value) {
|
||||
hasWarnedPersistFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.error({
|
||||
title: t('chat.training.errors.persistTitle'),
|
||||
message: `${t('chat.training.errors.persistBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
await persistQueue;
|
||||
@@ -251,10 +370,33 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
|
||||
const loadTrainingProgress = async () => {
|
||||
if (!isTrainingAgent.value) return;
|
||||
if (!hasAuthenticatedUser.value) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const record = await getMyTrainingProgress();
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(record);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
|
||||
if (error instanceof BusinessError && error.status === 401) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
return;
|
||||
}
|
||||
if (!hasWarnedLoadFailure.value) {
|
||||
hasWarnedLoadFailure.value = true;
|
||||
const message = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('errors.generic');
|
||||
msg.warning({
|
||||
title: t('chat.training.errors.loadTitle'),
|
||||
message: `${t('chat.training.errors.loadBody')}:${message}`,
|
||||
});
|
||||
}
|
||||
applyProgressRecord(null);
|
||||
} finally {
|
||||
isHydrated.value = true;
|
||||
@@ -290,26 +432,49 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
watch(currentAgent, (agent) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
}, { immediate: true });
|
||||
watch(
|
||||
[
|
||||
currentAgent,
|
||||
hasAuthenticatedUser,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([agent, loggedIn]) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
records.value = [];
|
||||
departmentOptions.value = [];
|
||||
stats.value = {
|
||||
total: 0,
|
||||
passed: 0,
|
||||
failed: 0,
|
||||
inProgress: 0,
|
||||
passRate: 0,
|
||||
averageScore: 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!loggedIn) {
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(null);
|
||||
isHydrated.value = true;
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingProgress();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
|
||||
[
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
hrKeyword,
|
||||
hrStatusFilter,
|
||||
hrDepartmentFilter,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
([enabled, canView]) => {
|
||||
if (!enabled || !canView) return;
|
||||
void loadAdminRecords();
|
||||
@@ -320,37 +485,66 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const markVideoCompleted = () => {
|
||||
stage.value = 'summary';
|
||||
// 立即推入本地助手消息(复盘卡片)
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
if (totalQuestionCount.value <= 0) {
|
||||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||||
return;
|
||||
}
|
||||
stage.value = 'exam';
|
||||
attemptCount.value += 1;
|
||||
resetExamState();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.startExamCommand'));
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const selectAnswer = (optionId: string) => {
|
||||
if (answerLocked.value || !currentQuestion.value) return;
|
||||
const answeredQuestion = currentQuestion.value;
|
||||
selectedOptionId.value = optionId;
|
||||
const isCorrect = optionId === currentQuestion.value.answer;
|
||||
const isCorrect = optionId === answeredQuestion.answer;
|
||||
currentFeedbackCorrect.value = isCorrect;
|
||||
if (isCorrect) {
|
||||
score.value += 5;
|
||||
}
|
||||
answerRecords.value.push({
|
||||
questionId: currentQuestion.value.id,
|
||||
const nextCorrectAnswerCount = correctCount.value + (isCorrect ? 1 : 0);
|
||||
const nextScore = calculateTrainingScore(nextCorrectAnswerCount, totalQuestionCount.value);
|
||||
score.value = nextScore;
|
||||
const answerRecord: TrainingAnswerRecord = {
|
||||
questionId: answeredQuestion.id,
|
||||
selectedOptionId: optionId,
|
||||
correct: isCorrect,
|
||||
});
|
||||
answerLocked.value = true;
|
||||
};
|
||||
answerRecords.value.push(answerRecord);
|
||||
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
|
||||
|
||||
// 推入用户选择的答案到聊天流
|
||||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||||
const label = getQuestionOptionLabel(answeredQuestion, optionId);
|
||||
void pushLocalUserMessage?.(label);
|
||||
|
||||
// [STEP 1] 最后一题直接进入结算,对齐文档里的“答完即公布最终成绩”。
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
latestSettledResult.value = {
|
||||
score: nextScore,
|
||||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||||
isPassed: nextScore >= passScore.value,
|
||||
};
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
|
||||
// [STEP 2] 非最后一题则在聊天流里自动反馈上一题,并紧接着展示下一题。
|
||||
currentQuestionIndex.value += 1;
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
@@ -364,7 +558,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
@@ -372,17 +566,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
latestExamFeedback.value = null;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
stage.value = 'summary';
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
void pushLocalUserMessage?.(t('chat.training.chatPrompts.restartExamCommand'));
|
||||
// 重新推回视频导学,强制补考再次完整经过“视频 -> 复盘 -> 开考”链路。
|
||||
void pushLocalAssistantMessage?.(learnerAssistantMessage.value);
|
||||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||||
};
|
||||
|
||||
const exportRecords = async () => {
|
||||
@@ -405,21 +601,14 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
const learnerChatPrompt = computed(() => {
|
||||
// 阶段 1:破冰与视频导学
|
||||
if (stage.value === 'video') {
|
||||
return `👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。\n\n▶️ 请先点击观看 [入职培训视频]。观看完毕后,请回复【已看完】。`;
|
||||
}
|
||||
// 阶段 2:知识点串讲
|
||||
if (stage.value === 'summary') {
|
||||
return `${t('chat.training.chatPrompts.afterVideo')}\n\n参考知识点:\n${summaryPoints.value.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
|
||||
}
|
||||
// 阶段 4:结算
|
||||
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
|
||||
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
|
||||
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.afterPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.afterFail', { score: score.value });
|
||||
}
|
||||
// 阶段 3:互动测试
|
||||
return t('chat.training.chatPrompts.examInProgress', {
|
||||
index: currentQuestionIndex.value + 1,
|
||||
total: totalQuestionCount.value,
|
||||
@@ -427,11 +616,36 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 新建培训聊天会话时使用的统一提醒文案。
|
||||
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
|
||||
*/
|
||||
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
|
||||
passScore: passScore.value,
|
||||
}));
|
||||
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
|
||||
|
||||
const learnerAssistantMessage = computed(() => {
|
||||
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
|
||||
if (stage.value === 'video') {
|
||||
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
|
||||
}
|
||||
if (stage.value === 'summary') {
|
||||
return buildSummaryAssistantMessage();
|
||||
}
|
||||
if (stage.value === 'result') {
|
||||
return isPassed.value
|
||||
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
|
||||
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
|
||||
}
|
||||
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
|
||||
});
|
||||
|
||||
const showVideoModal = ref(false);
|
||||
const videoUrl = computed(() => {
|
||||
const extraConfig = currentAgent.value?.extra_config || {};
|
||||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||||
return customUrl || DEFAULT_TRAINING_VIDEO_URL;
|
||||
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
|
||||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||||
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
|
||||
});
|
||||
|
||||
return {
|
||||
@@ -443,12 +657,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentQuestionIndex,
|
||||
currentQuestion,
|
||||
totalQuestionCount,
|
||||
passScore,
|
||||
answeredCount,
|
||||
score,
|
||||
attemptCount,
|
||||
selectedOptionId,
|
||||
answerLocked,
|
||||
currentFeedbackCorrect,
|
||||
latestExamFeedback,
|
||||
latestSettledResult,
|
||||
answerRecords,
|
||||
completionDate,
|
||||
summaryPoints,
|
||||
@@ -467,6 +684,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
filteredRecords,
|
||||
stats,
|
||||
learnerChatPrompt,
|
||||
newSessionReminderMessage,
|
||||
shouldShowNewSessionReminder,
|
||||
learnerAssistantMessage,
|
||||
managementChatPrompt,
|
||||
markVideoCompleted,
|
||||
startExam,
|
||||
|
||||
@@ -92,6 +92,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
getCurrentQuestionIndex: () => workspace.currentQuestionIndex.value,
|
||||
getAnsweredCount: () => workspace.answeredCount.value,
|
||||
getTotalCount: () => workspace.totalQuestionCount.value,
|
||||
getPassScore: () => workspace.passScore.value,
|
||||
getScore: () => workspace.score.value,
|
||||
getSelectedOptionId: () => workspace.selectedOptionId.value,
|
||||
getAnswerLocked: () => workspace.answerLocked.value,
|
||||
@@ -101,6 +102,7 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
if (!q) return '';
|
||||
return q.options?.find((o) => o.id === workspace.selectedOptionId.value)?.label || '';
|
||||
},
|
||||
getLatestExamFeedback: () => workspace.latestExamFeedback.value,
|
||||
onSelect: workspace.selectAnswer,
|
||||
onNext: workspace.moveToNextQuestion,
|
||||
onPlayVideo: () => {
|
||||
@@ -110,8 +112,10 @@ export function createTrainingHandlers(workspace: TrainingHandlerSource): Traini
|
||||
},
|
||||
onStartExam: workspace.startExam,
|
||||
onRestartExam: workspace.restartExam,
|
||||
getCorrectCount: () => workspace.correctCount.value,
|
||||
getWrongCount: () => workspace.wrongCount.value,
|
||||
getCorrectCount: () => workspace.latestSettledResult.value?.correctCount ?? workspace.correctCount.value,
|
||||
getWrongCount: () => workspace.latestSettledResult.value?.wrongCount ?? workspace.wrongCount.value,
|
||||
getResultScore: () => workspace.latestSettledResult.value?.score ?? workspace.score.value,
|
||||
getResultPassed: () => workspace.latestSettledResult.value?.isPassed ?? workspace.isPassed.value,
|
||||
getSummaryPoints: () => workspace.summaryPoints.value,
|
||||
getSummaryChecklist: () => workspace.summaryChecklist.value,
|
||||
};
|
||||
|
||||
@@ -64,6 +64,7 @@ export interface ChatPageMarkdownContext {
|
||||
handleLeaveMarkdownClick: (event: MouseEvent) => void;
|
||||
parsePlmPreviewLink: (href: string) => SourceFileLink | null;
|
||||
openPreview: (file: SourceFileLink) => Promise<void>;
|
||||
openAssetHistory: (assetId: string, assetName?: string) => void;
|
||||
getMessageLinks: (message: Record<string, unknown>) => SourceFileLink[];
|
||||
getDisplayRetrieverResources: (msgItem: Record<string, unknown>) => Record<string, unknown>[];
|
||||
getSourceLinks: (resources?: unknown[]) => SourceFileLink[];
|
||||
@@ -178,6 +179,47 @@ function downloadInlineFile(file: InlineDownloadFile): void {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
|
||||
function normalizeAssetHistoryText(value: string): string {
|
||||
const normalized = String(value || '').trim();
|
||||
if (!normalized || normalized === '-' || normalized === '无') return '';
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把聊天结果表格里的“资产编号”列增强为可点击入口。
|
||||
* 核心逻辑:只处理包含“资产编号”表头的表格,并从同行“资产名称”列一并带出检索关键词,避免误伤其他普通 Markdown 表格。
|
||||
*/
|
||||
function enhanceAssetHistoryTableLinks(html: string): string {
|
||||
if (!html || typeof document === 'undefined' || !html.includes('<table')) return html;
|
||||
const container = document.createElement('div');
|
||||
container.innerHTML = html;
|
||||
const tables = Array.from(container.querySelectorAll('table'));
|
||||
tables.forEach((table) => {
|
||||
const headerCells = Array.from(table.querySelectorAll('thead th'));
|
||||
if (headerCells.length === 0) return;
|
||||
const headerLabels = headerCells.map((cell) => normalizeAssetHistoryText(cell.textContent || ''));
|
||||
const assetIdIndex = headerLabels.findIndex((label) => label === '资产编号');
|
||||
if (assetIdIndex < 0) return;
|
||||
const assetNameIndex = headerLabels.findIndex((label) => label === '资产名称');
|
||||
const rows = Array.from(table.querySelectorAll('tbody tr'));
|
||||
rows.forEach((row) => {
|
||||
const cells = Array.from(row.querySelectorAll('td'));
|
||||
const assetIdCell = cells[assetIdIndex];
|
||||
if (!assetIdCell) return;
|
||||
const assetId = normalizeAssetHistoryText(assetIdCell.textContent || '');
|
||||
if (!assetId) return;
|
||||
const assetName = assetNameIndex >= 0 ? normalizeAssetHistoryText(cells[assetNameIndex]?.textContent || '') : '';
|
||||
const link = document.createElement('a');
|
||||
link.href = `#asset-history?asset_id=${encodeURIComponent(assetId)}&asset_name=${encodeURIComponent(assetName)}`;
|
||||
link.className = 'chat-asset-history-link';
|
||||
link.textContent = assetId;
|
||||
assetIdCell.innerHTML = '';
|
||||
assetIdCell.appendChild(link);
|
||||
});
|
||||
});
|
||||
return container.innerHTML;
|
||||
}
|
||||
|
||||
export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const shouldRenderMessage = (msgItem: ChatMessage): boolean => {
|
||||
if (msgItem?.role === 'user') return true;
|
||||
@@ -226,7 +268,34 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
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') || '');
|
||||
const rawHref = anchor?.getAttribute('href') || '';
|
||||
// #region debug-point A:asset-history-anchor-click
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
fetch('http://127.0.0.1:7777/event', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
sessionId: 'asset-history-click',
|
||||
runId: 'pre-fix',
|
||||
hypothesisId: 'A',
|
||||
location: 'frontend/useChatPageMarkdown.ts',
|
||||
msg: '[DEBUG] asset history anchor clicked',
|
||||
data: {
|
||||
href: rawHref,
|
||||
tagName: target?.tagName || '',
|
||||
anchorText: String(anchor?.textContent || '').trim(),
|
||||
},
|
||||
ts: Date.now(),
|
||||
}),
|
||||
}).catch(() => {});
|
||||
}
|
||||
// #endregion
|
||||
if (rawHref.startsWith('#asset-history?')) {
|
||||
event.preventDefault();
|
||||
const params = new URLSearchParams(rawHref.slice('#asset-history?'.length));
|
||||
ctx.openAssetHistory((params.get('asset_id') || '').trim(), (params.get('asset_name') || '').trim());
|
||||
return;
|
||||
}
|
||||
const preview = ctx.parsePlmPreviewLink(rawHref);
|
||||
if (preview) {
|
||||
event.preventDefault();
|
||||
void ctx.openPreview(preview);
|
||||
@@ -248,7 +317,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
try {
|
||||
const rendered = marked.parse(displayText);
|
||||
const html = typeof rendered === 'string' ? rendered : displayText;
|
||||
return html
|
||||
return enhanceAssetHistoryTableLinks(html)
|
||||
.replace(/<(td|th)\b([^>]*)>(?:\s| |<br\s*\/?>)*<\/\1>/gi, (_match, tagName: string, attrs: string) => (
|
||||
`<${tagName}${attrs}>无</${tagName}>`
|
||||
))
|
||||
@@ -263,6 +332,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
||||
const messageBubbleHandlers: ChatMessageBubbleHandlers = {
|
||||
renderMarkdown,
|
||||
onMarkdownClick: handleChatMarkdownClick,
|
||||
openAssetHistory: ctx.openAssetHistory,
|
||||
getInlineDownloadFiles: safeExtractInlineDownloadFiles,
|
||||
downloadInlineFile,
|
||||
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
|
||||
|
||||
@@ -25,12 +25,29 @@ export interface TrainingQuestion {
|
||||
options?: TrainingQuestionOption[];
|
||||
}
|
||||
|
||||
export interface TrainingContentConfig {
|
||||
passScore: number;
|
||||
summaryPoints: string[];
|
||||
summaryChecklist: string[];
|
||||
questionBank: TrainingQuestion[];
|
||||
}
|
||||
|
||||
export interface TrainingAnswerRecord {
|
||||
questionId: string;
|
||||
selectedOptionId: string;
|
||||
correct: boolean;
|
||||
}
|
||||
|
||||
export interface TrainingExamTransitionFeedback {
|
||||
questionId: string;
|
||||
questionPrompt: string;
|
||||
selectedAnswerLabel: string;
|
||||
correctAnswerLabel: string;
|
||||
explanation: string;
|
||||
correct: boolean;
|
||||
scoreAfterAnswer: number;
|
||||
}
|
||||
|
||||
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
|
||||
|
||||
export interface TrainingRecord {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* features/chat/training/trainingWorkspace.utils.ts
|
||||
* 用途:沉淀新人培训工作区的纯函数规则,便于前端复用与单测。
|
||||
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
|
||||
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
|
||||
*/
|
||||
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
extra_config?: Record<string, unknown> | null;
|
||||
} | null | undefined;
|
||||
|
||||
export type TrainingGuideLike = {
|
||||
id?: number | null;
|
||||
file_type?: string | null;
|
||||
guide_usage?: string | null;
|
||||
file_url?: string | null;
|
||||
file_path?: string | null;
|
||||
} | null | undefined;
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> => (
|
||||
value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: {}
|
||||
);
|
||||
|
||||
const normalizeStringList = (value: unknown): string[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
const normalizePassScore = (value: unknown, fallback: number): number => {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) return fallback;
|
||||
return Math.max(0, Math.min(100, Math.round(parsed)));
|
||||
};
|
||||
|
||||
const normalizeQuestionOptionList = (value: unknown): TrainingQuestionOption[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item, index) => {
|
||||
if (typeof item === 'string') {
|
||||
const label = item.trim();
|
||||
if (!label) return null;
|
||||
return {
|
||||
id: String.fromCharCode(97 + index),
|
||||
label,
|
||||
};
|
||||
}
|
||||
const raw = asRecord(item);
|
||||
const id = String(raw.id || '').trim() || String.fromCharCode(97 + index);
|
||||
const label = String(raw.label || '').trim();
|
||||
if (!label) return null;
|
||||
return { id, label };
|
||||
})
|
||||
.filter((item): item is TrainingQuestionOption => Boolean(item));
|
||||
};
|
||||
|
||||
const normalizeQuestionBank = (
|
||||
value: unknown,
|
||||
booleanOptions: TrainingQuestionOption[],
|
||||
): TrainingQuestion[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value
|
||||
.map((item, index): TrainingQuestion | null => {
|
||||
const raw = asRecord(item);
|
||||
const type: TrainingQuestion['type'] = raw.type === 'boolean' ? 'boolean' : 'single';
|
||||
const prompt = String(raw.prompt || '').trim();
|
||||
if (!prompt) return null;
|
||||
const options = type === 'boolean'
|
||||
? booleanOptions
|
||||
: normalizeQuestionOptionList(raw.options);
|
||||
if (type === 'single' && options.length < 2) return null;
|
||||
const fallbackAnswer = type === 'boolean'
|
||||
? 'true'
|
||||
: String(options[0]?.id || '').trim();
|
||||
const answer = String(raw.answer || '').trim();
|
||||
const optionIds = options.map((option) => option.id);
|
||||
return {
|
||||
id: String(raw.id || '').trim() || `q${index + 1}`,
|
||||
type,
|
||||
prompt,
|
||||
answer: optionIds.includes(answer) ? answer : fallbackAnswer,
|
||||
explanation: String(raw.explanation || '').trim(),
|
||||
options,
|
||||
};
|
||||
})
|
||||
.filter((item): item is TrainingQuestion => Boolean(item));
|
||||
};
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用培训工作区。
|
||||
* AI 触发时机:当聊天页需要决定是否渲染“视频 -> 总结 -> 答题”培训主链时使用,优先读取显式配置,避免误伤普通 Agent。
|
||||
*/
|
||||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
if (extraConfig.training_workspace_enabled === false || extraConfig.training_workspace_enabled === 'false') {
|
||||
return false;
|
||||
}
|
||||
const explicitFlags = [
|
||||
extraConfig.training_workspace_enabled,
|
||||
extraConfig.training_mode,
|
||||
extraConfig.training_agent,
|
||||
];
|
||||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||||
return true;
|
||||
}
|
||||
const name = String(agent?.name || '').trim();
|
||||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析培训视频地址。
|
||||
* AI 触发时机:当培训工作区需要决定播放哪个培训视频时使用,若 Agent 未配置专属视频,则回退到默认地址。
|
||||
*/
|
||||
export function resolveTrainingVideoUrl(agent: TrainingAgentLike, fallbackUrl: string): string {
|
||||
const extraConfig = agent?.extra_config || {};
|
||||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||||
return customUrl || fallbackUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找培训工作区优先使用的视频指南。
|
||||
* AI 触发时机:当培训工作区需要从后台上传资料中挑选正式培训视频时使用,优先选显式标记为 training_video 的文件。
|
||||
*/
|
||||
export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
||||
const normalized = Array.isArray(guides) ? guides : [];
|
||||
return (
|
||||
normalized.find((guide) => guide?.guide_usage === 'training_video' && guide?.file_type === 'video')
|
||||
|| normalized.find((guide) => guide?.file_type === 'video')
|
||||
|| null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找培训工作区优先使用的试题 PDF。
|
||||
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
|
||||
*/
|
||||
export function resolveTrainingExamPdfGuide(guides: TrainingGuideLike[] | null | undefined): TrainingGuideLike {
|
||||
const normalized = Array.isArray(guides) ? guides : [];
|
||||
return (
|
||||
normalized.find((guide) => guide?.guide_usage === 'training_exam_pdf' && guide?.file_type === 'pdf')
|
||||
|| null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析培训工作区的后台配置。
|
||||
* AI 触发时机:当培训工作区需要优先消费 Agent extra_config 中的题库、复盘要点和及格线时使用;若后台未配置,则逐项回退到前端默认值。
|
||||
*/
|
||||
export function resolveTrainingContentConfig(
|
||||
agent: TrainingAgentLike,
|
||||
fallback: TrainingContentConfig,
|
||||
booleanOptions: TrainingQuestionOption[],
|
||||
): TrainingContentConfig {
|
||||
const extraConfig = asRecord(agent?.extra_config);
|
||||
const trainingConfig = asRecord(extraConfig.training_config);
|
||||
const mergedConfig = {
|
||||
...extraConfig,
|
||||
...trainingConfig,
|
||||
};
|
||||
|
||||
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
|
||||
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
|
||||
const questionBank = normalizeQuestionBank(
|
||||
mergedConfig.question_bank ?? mergedConfig.questionBank,
|
||||
booleanOptions,
|
||||
);
|
||||
|
||||
return {
|
||||
passScore: normalizePassScore(
|
||||
mergedConfig.pass_score ?? mergedConfig.passScore,
|
||||
fallback.passScore || DEFAULT_PASS_SCORE,
|
||||
),
|
||||
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,
|
||||
summaryChecklist: summaryChecklist.length ? summaryChecklist : fallback.summaryChecklist,
|
||||
questionBank: questionBank.length ? questionBank : fallback.questionBank,
|
||||
};
|
||||
}
|
||||
@@ -21,7 +21,7 @@ export interface RetrieverResource {
|
||||
export interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result';
|
||||
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result' | 'maintenance-device-result';
|
||||
retriever_resources?: RetrieverResource[];
|
||||
attribution_parts?: string[];
|
||||
chat_log_id?: number;
|
||||
@@ -99,6 +99,24 @@ export interface ChatSourceFileResult {
|
||||
source_ext?: string;
|
||||
}
|
||||
|
||||
export interface AssetHistoryFileItem {
|
||||
name: string;
|
||||
path: string;
|
||||
relative_path: string;
|
||||
url: string;
|
||||
actual_ext?: string;
|
||||
size_bytes?: number;
|
||||
modified_at?: string;
|
||||
match_reason?: string;
|
||||
}
|
||||
|
||||
export interface AssetHistorySearchResult {
|
||||
asset_id?: string;
|
||||
asset_name?: string;
|
||||
total: number;
|
||||
items: AssetHistoryFileItem[];
|
||||
}
|
||||
|
||||
export interface ChatUploadResult {
|
||||
id: string;
|
||||
name?: string;
|
||||
|
||||
Reference in new issue
Block a user