Merge branch 'dev' into hugo-shipping-notice

This commit is contained in:
hugo committed 2026-06-30 21:01:57 +08:00
commit 9f5493185d
29 files changed
+3957 -12

No files matched your search

@@ -0,0 +1,200 @@
/**
* features/chat/api/training.api.ts
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
* 依赖:shared/api/client、auth headers、training.types。
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
type TrainingRecordApi = {
id: number;
user_id?: number;
employee_id?: string | null;
name?: string | null;
department?: string | null;
join_date?: string | null;
stage?: TrainingStage;
current_question_index?: number;
score?: number;
passed?: boolean;
attempt_count?: number;
answer_details?: Array<{
question_id?: string;
selected_option_id?: string;
correct?: boolean;
}>;
completion_time?: string | null;
updated_at?: string | null;
started_at?: string | null;
status?: TrainingRecord['status'];
};
type TrainingListApi = {
items: TrainingRecordApi[];
total: number;
page: number;
page_size: number;
pages: number;
department_options: string[];
};
type TrainingStatsApi = {
total: number;
passed: number;
failed: number;
in_progress: number;
pass_rate: number;
average_score: number;
};
export interface TrainingRecordQuery {
keyword?: string;
department?: string;
status?: 'all' | 'passed' | 'failed' | 'in_progress';
page?: number;
page_size?: number;
}
export interface SaveTrainingProgressPayload {
stage: TrainingStage;
currentQuestionIndex: number;
score: number;
passed: boolean;
attemptCount: number;
answerDetails: TrainingAnswerRecord[];
joinDate?: string | null;
}
const authHeaders = () => ({ headers: getAuthHeaders() });
const jsonAuthHeaders = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): TrainingAnswerRecord[] {
return Array.isArray(items)
? items.map((item) => ({
questionId: String(item.question_id || ''),
selectedOptionId: String(item.selected_option_id || ''),
correct: Boolean(item.correct),
}))
: [];
}
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
return {
id: data.id,
name: String(data.name || ''),
employeeId: String(data.employee_id || ''),
department: String(data.department || ''),
joinDate: String(data.join_date || ''),
completionDate: data.completion_time ? String(data.completion_time).slice(0, 10) : null,
score: typeof data.score === 'number' ? data.score : null,
attempts: Number(data.attempt_count || 0),
status: data.status || 'in_progress',
stage: (data.stage || 'video') as TrainingStage,
currentQuestionIndex: Number(data.current_question_index || 0),
passed: Boolean(data.passed),
answerDetails: mapAnswerDetails(data.answer_details),
startedAt: data.started_at || null,
completionTime: data.completion_time || null,
updatedAt: data.updated_at || null,
};
}
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
const progress = mapTrainingProgressRecord(data);
return {
id: progress.id,
name: progress.name,
employeeId: progress.employeeId,
department: progress.department,
joinDate: progress.joinDate,
completionDate: progress.completionDate,
score: progress.score,
attempts: progress.attempts,
status: progress.status,
};
}
function buildQueryString(query: TrainingRecordQuery = {}) {
const params = new URLSearchParams();
if (query.keyword) params.set('keyword', query.keyword);
if (query.department) params.set('department', query.department);
if (query.status) params.set('status', query.status);
if (query.page) params.set('page', String(query.page));
if (query.page_size) params.set('page_size', String(query.page_size));
return params.toString();
}
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
return data ? mapTrainingProgressRecord(data) : null;
}
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
method: 'PUT',
...jsonAuthHeaders(),
body: JSON.stringify({
stage: payload.stage,
current_question_index: payload.currentQuestionIndex,
score: payload.score,
passed: payload.passed,
attempt_count: payload.attemptCount,
answer_details: payload.answerDetails.map((item) => ({
question_id: item.questionId,
selected_option_id: item.selectedOptionId,
correct: item.correct,
})),
join_date: payload.joinDate || undefined,
}),
});
return mapTrainingProgressRecord(data);
}
export async function listTrainingRecords(query: TrainingRecordQuery = {}) {
const qs = buildQueryString(query);
const data = await requestJson<TrainingListApi>(`/api/admin/training-records${qs ? `?${qs}` : ''}`, authHeaders());
return {
items: data.items.map(mapTrainingRecord),
total: data.total,
page: data.page,
pageSize: data.page_size,
pages: data.pages,
departmentOptions: data.department_options || [],
};
}
export async function getTrainingStats(query: TrainingRecordQuery = {}): Promise<TrainingStats> {
const qs = buildQueryString(query);
const data = await requestJson<TrainingStatsApi>(`/api/admin/training-records/stats${qs ? `?${qs}` : ''}`, authHeaders());
return {
total: Number(data.total || 0),
passed: Number(data.passed || 0),
failed: Number(data.failed || 0),
inProgress: Number(data.in_progress || 0),
passRate: Number(data.pass_rate || 0),
averageScore: Number(data.average_score || 0),
};
}
export async function exportTrainingRecords(query: TrainingRecordQuery = {}): Promise<void> {
const qs = buildQueryString(query);
const response = await fetch(`/api/admin/training-records/export${qs ? `?${qs}` : ''}`, {
method: 'GET',
headers: getAuthHeaders(),
});
if (!response.ok) {
throw new Error(`Export failed: HTTP ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `training_records_${new Date().toISOString().slice(0, 10)}.xlsx`;
document.body.appendChild(link);
link.click();
link.remove();
URL.revokeObjectURL(url);
}
@@ -174,9 +174,9 @@ watch(
</script>
<template>
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<footer class="safe-bottom z-20 shrink-0 bg-transparent p-2 md:p-3">
<div class="relative mx-auto max-w-4xl">
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<div class="flex flex-col rounded-2xl bg-surface p-1.5 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<div
v-if="isShippingNoticeAgent && shippingFocusTaskNo"
class="mb-2 flex items-center gap-2 rounded-xl bg-brand-500 px-3 py-2 text-xs font-medium text-white"
@@ -198,8 +198,8 @@ watch(
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : shippingFocusTaskNo ? $t('chat.shippingNoticeUi.focusInputPlaceholder', { taskId: shippingFocusTaskNo }) : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 44px; max-height: 220px;"
class="w-full resize-none border-none bg-transparent px-2.5 py-1.5 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 40px; max-height: 220px;"
:disabled="isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
@@ -253,7 +253,7 @@ watch(
<span>点发送开始处理</span>
</div>
<div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
<div class="flex items-center gap-3">
<button
type="button"
@@ -10,6 +10,7 @@ import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/Ch
import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue';
import type { TrainingHandlers } from './messages/TrainingExamQuestionMessage.vue';
import type { ChatMessage } from '../types/chat.types';
import type { ToolRunProgress } from '../api/toolRunProgress.api';
@@ -31,6 +32,7 @@ const {
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
trainingHandlers: TrainingHandlers;
shouldRenderMessage: (msg: ChatMessage) => boolean;
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage, index: number) => boolean;
getMessageRunProgress: (msg: ChatMessage) => ToolRunProgress | null;
@@ -39,6 +41,8 @@ const {
toolRunProgress: ToolRunProgress | null;
toolRunProgressTitle: string;
showScrollToBottom: boolean;
hideWelcomePanel?: boolean;
pinMessagesToBottom?: boolean;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
}>();
@@ -74,9 +78,9 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
<div :class="messages.length === 0 ? 'h-full' : pinMessagesToBottom === false ? 'min-h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0"
v-if="messages.length === 0 && !hideWelcomePanel"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
@@ -97,6 +101,7 @@ const getMessageKey = (msg: ChatMessage, index: number) => (
:handlers="handlers"
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
:training-handlers="trainingHandlers"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@@ -5,6 +5,7 @@
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
*/
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { Loader2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
@@ -14,9 +15,19 @@ import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
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 { useChatPageContext } from '@/features/chat/composables/chat.context';
import { matchesTrainingAgent } from '@/features/chat/composables/useTrainingWorkspace';
const page = useChatPageContext();
const isTrainingAgentPage = computed(() => matchesTrainingAgent(page.currentAgent));
const hideWelcomePanel = computed(() => isTrainingAgentPage.value);
const isTrainingWorkspaceExpanded = ref(false);
// 切换 Agent 时,重置工作区展开状态,确保每次进入都是收起状态(聊天优先)
watch(() => page.currentAgentId, () => {
isTrainingWorkspaceExpanded.value = false;
});
</script>
<template>
@@ -84,8 +95,18 @@ const page = useChatPageContext();
</div>
<template v-else>
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<div class="flex min-h-0 min-w-0 flex-1">
<div class="flex min-h-0 min-w-0 flex-1 flex-col">
<TrainingWorkspacePanel
:current-agent="page.currentAgent"
:current-user="page.currentUser"
:has-messages="page.messages.length > 0"
:training="page.training"
@send-chat-prompt="page.handleSend($event)"
@push-local-assistant-message="page.pushLocalAssistantMessage($event)"
@update:expanded="isTrainingWorkspaceExpanded = $event"
/>
<ShippingBatchProgressPanel
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
:conversation-workspace="page.shippingConversationWorkspace"
@@ -99,6 +120,7 @@ const page = useChatPageContext();
/>
<ChatMessageList
v-show="!isTrainingWorkspaceExpanded"
:messages="page.messages"
:agent-name="page.currentAgent?.name || 'AI'"
:suggested-questions-style="page.suggestedQuestionsStyle"
@@ -112,6 +134,7 @@ const page = useChatPageContext();
:handlers="page.messageBubbleHandlers"
:leave-handlers="page.leaveMessageHandlers"
:shipping-handlers="page.shippingMappingHandlers"
:training-handlers="page.trainingHandlers"
:should-render-message="page.shouldRenderMessage"
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
:get-message-run-progress="page.getMessageRunProgress"
@@ -120,6 +143,8 @@ const page = useChatPageContext();
:tool-run-progress="page.toolRunProgress"
:tool-run-progress-title="page.toolRunProgressTitle"
:show-scroll-to-bottom="page.showScrollToBottom"
:hide-welcome-panel="hideWelcomePanel"
:pin-messages-to-bottom="!isTrainingAgentPage"
:scroll-container-holder="page.scrollContainerHolder"
@copy="page.copyToClipboard($event.message, $event.index)"
@edit="page.input = $event"
@@ -131,6 +156,7 @@ const page = useChatPageContext();
/>
<ChatInputBar
v-show="!isTrainingWorkspaceExpanded"
:key="`${page.currentAgentId}-${page.conversationId || 'draft'}-${page.messages.length}`"
v-model="page.input"
v-model:selected-kb="page.selectedKb"
@@ -0,0 +1,819 @@
<script setup lang="ts">
/**
* features/chat/components/TrainingWorkspacePanel.vue
* 用途:在培训 Agent 的聊天页顶部提供“学员考试流 + HR 管理流”一体化工作区。
* 依赖:useTrainingWorkspace、lucide 图标、聊天页 currentAgent/currentUser。
* 逻辑:只在培训 Agent 下渲染;学员端负责前端交互闭环,HR 端负责本地筛选统计与 Excel 导出,并可把上下文同步回聊天区。
*/
import { computed, reactive, ref, watch, type ShallowUnwrapRef } from 'vue';
import { useI18n } from 'vue-i18n';
import {
BarChart3,
BookOpen,
CheckCircle2,
ChevronDown,
ChevronUp,
ClipboardCheck,
Download,
PlayCircle,
RefreshCcw,
Send,
ShieldCheck,
Target,
Users,
XCircle,
} from 'lucide-vue-next';
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
const props = defineProps<{
currentAgent: Record<string, unknown> | null;
currentUser: Record<string, unknown> | null;
hasMessages: boolean;
training: ShallowUnwrapRef<ReturnType<typeof useTrainingWorkspace>>;
}>();
const emit = defineEmits<{
'send-chat-prompt': [prompt: string];
'push-local-assistant-message': [content: string];
'update:expanded': [expanded: boolean];
}>();
const { t } = useI18n();
const workspace = reactive(props.training);
// 将 workspace 内部控制弹窗的状态同步给组件本地变量(如果需要,或者直接用 workspace.showVideoModal)
const showVideoModal = computed({
get: () => workspace.showVideoModal,
set: (val) => { workspace.showVideoModal = val; }
});
const lastVideoTime = ref(0);
const stageStep = computed(() => {
if (workspace.stage === 'video') return 1;
if (workspace.stage === 'summary') return 2;
if (workspace.stage === 'exam') return 3;
return 4;
});
const stageItems = computed(() => ([
{ key: 'video', label: 'chat.training.steps.video', icon: PlayCircle },
{ key: 'summary', label: 'chat.training.steps.summary', icon: BookOpen },
{ key: 'exam', label: 'chat.training.steps.exam', icon: ClipboardCheck },
{ key: 'result', label: 'chat.training.steps.result', icon: ShieldCheck },
]));
const userExpandedOverride = ref(false);
const handleVideoTimeUpdate = (e: Event) => {
const video = e.target as HTMLVideoElement;
if (!video.seeking) {
lastVideoTime.value = video.currentTime;
}
};
const handleVideoSeeking = (e: Event) => {
const video = e.target as HTMLVideoElement;
if (video.currentTime > lastVideoTime.value + 1) {
video.currentTime = lastVideoTime.value;
}
};
const handleVideoEnded = () => {
showVideoModal.value = false;
workspace.markVideoCompleted();
};
const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
workspaceExpanded.value = expanded;
emit('update:expanded', expanded);
if (manual) {
userExpandedOverride.value = expanded;
} else if (!expanded) {
userExpandedOverride.value = 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 || '';
});
// 默认进入 Chat 聊天页面(即收起工作区状态)
const workspaceExpanded = ref(false);
const autoSyncInitialPrompt = () => {
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
emit('push-local-assistant-message', workspace.learnerChatPrompt);
}
};
// 监听 Agent 切换,重置所有本地交互状态,确保每次进入都是初始、收起且触发引导的状态
watch(
() => props.currentAgent?.id,
() => {
userExpandedOverride.value = false;
workspaceExpanded.value = false;
emit('update:expanded', false);
},
{ immediate: true }
);
watch(() => props.hasMessages, () => {
// 如果用户没有手动展开,且消息状态变化,我们保持在聊天模式(收起工作区)
if (!userExpandedOverride.value) {
workspaceExpanded.value = false;
emit('update:expanded', false);
}
});
watch(
() => workspace.isHydrated,
(ready) => {
if (ready && workspace.isTrainingAgent && !props.hasMessages) {
autoSyncInitialPrompt();
}
},
);
const isCompactMode = computed(() => !workspaceExpanded.value);
const compactSummary = computed(() => {
if (workspace.activeView === 'admin') {
return `${workspace.stats.total}${t('chat.training.hr.stats.total')} / ${workspace.stats.passRate}% ${t('chat.training.hr.stats.passRate')}`;
}
if (workspace.stage === 'video') return t('chat.training.video.title');
if (workspace.stage === 'summary') return t('chat.training.summary.title');
if (workspace.stage === 'exam') {
return t('chat.training.exam.questionCounter', {
current: workspace.answeredCount + 1,
total: workspace.totalQuestionCount,
});
}
return workspace.isPassed ? t('chat.training.result.passTitle') : t('chat.training.result.failTitle');
});
</script>
<template>
<section
v-if="workspace.isTrainingAgent"
class="mx-auto w-full max-w-6xl rounded-3xl border border-brand-100 bg-gradient-to-br from-white via-brand-50/30 to-slate-50 shadow-sm"
:class="workspaceExpanded ? 'mb-0 min-h-0 flex-1 overflow-y-auto' : 'mb-4 min-w-0 flex-none'"
>
<div
v-if="isCompactMode"
class="flex flex-col gap-2 bg-white/90 px-4 py-2.5 backdrop-blur-sm md:px-5"
>
<div class="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="inline-flex items-center gap-2 rounded-full bg-brand-50 px-3 py-1 text-[11px] font-semibold text-brand-700">
<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>
</div>
<div class="mt-1.5 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'learner' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'learner'"
>
{{ $t('chat.training.tabs.learner') }}
</button>
<button
v-if="workspace.isAdminViewer"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'admin'"
>
{{ $t('chat.training.tabs.admin') }}
</button>
</div>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<button
v-if="workspace.stage === 'video'"
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="showVideoModal = true"
>
<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"
@click="setWorkspaceExpanded(true, true)"
>
<ChevronDown class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.expandWorkspace') }}</span>
</button>
</div>
</div>
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-4 py-2.5 md:flex-row md:items-center md:justify-between">
<div class="min-w-0">
<div class="truncate text-sm font-semibold text-primary">
{{ compactSummary }}
</div>
<div class="mt-1 text-xs leading-5 text-secondary">
<template v-if="workspace.activeView === 'admin'">
{{ $t('chat.training.hr.filters.keywordLabel') }}: {{ workspace.hrKeyword || $t('chat.training.hr.filters.noLimit') }}
· {{ $t('chat.training.hr.filters.departmentLabel') }}:
{{ workspace.hrDepartmentFilter === 'all' ? $t('chat.training.hr.filters.allDepartments') : workspace.hrDepartmentFilter }}
</template>
<template v-else>
{{ $t('chat.training.progressPercent') }}: {{ workspace.learnerProgressPercent }}%
· {{ $t('chat.training.learnerCard.name') }}: {{ workspace.currentUserName }}
</template>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 text-xs">
<div class="rounded-full bg-white px-3 py-1.5 font-medium text-primary shadow-sm">
{{ workspace.activeView === 'admin' ? `${$t('chat.training.hr.stats.passRate')} ${workspace.stats.passRate}%` : `${$t('chat.training.progressPercent')} ${workspace.learnerProgressPercent}%` }}
</div>
<div class="rounded-full bg-white px-3 py-1.5 font-medium text-primary shadow-sm">
{{ workspace.activeView === 'admin' ? `${$t('chat.training.hr.stats.total')} ${workspace.stats.total}` : `${$t('chat.training.result.scoreLabel')} ${workspace.score}` }}
</div>
</div>
</div>
</div>
<div v-else class="flex flex-col gap-2 bg-white/90 px-4 py-2.5 backdrop-blur-sm md:px-5">
<div class="flex flex-col gap-2 xl:flex-row xl:items-center xl:justify-between">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="inline-flex items-center gap-2 rounded-full bg-brand-50 px-3 py-1 text-[11px] font-semibold text-brand-700">
<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>
</div>
<div class="mt-1.5 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'learner' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'learner'"
>
{{ $t('chat.training.tabs.learner') }}
</button>
<button
v-if="workspace.isAdminViewer"
type="button"
class="rounded-full px-3 py-1.5 text-xs font-medium transition"
:class="workspace.activeView === 'admin' ? 'bg-brand-600 text-white' : 'bg-surface-soft text-secondary hover:bg-slate-100'"
@click="workspace.activeView = 'admin'"
>
{{ $t('chat.training.tabs.admin') }}
</button>
</div>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<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"
@click="setWorkspaceExpanded(false, true)"
>
<ChevronUp class="h-4 w-4 shrink-0" />
<span class="leading-none">{{ $t('chat.training.actions.collapseWorkspace') }}</span>
</button>
</div>
</div>
<div class="flex flex-col gap-2 rounded-2xl border border-brand-100 bg-brand-50/40 px-4 py-2.5 md:flex-row md:items-center md:justify-between">
<div class="min-w-0">
<div class="truncate text-sm font-semibold text-primary">
{{ compactSummary }}
</div>
<div class="mt-1 text-xs leading-5 text-secondary">
<template v-if="workspace.activeView === 'admin'">
{{ $t('chat.training.hr.filters.keywordLabel') }}: {{ workspace.hrKeyword || $t('chat.training.hr.filters.noLimit') }}
· {{ $t('chat.training.hr.filters.departmentLabel') }}:
{{ workspace.hrDepartmentFilter === 'all' ? $t('chat.training.hr.filters.allDepartments') : workspace.hrDepartmentFilter }}
</template>
<template v-else>
{{ $t('chat.training.progressPercent') }}: {{ workspace.learnerProgressPercent }}%
· {{ $t('chat.training.learnerCard.name') }}: {{ workspace.currentUserName }}
</template>
</div>
</div>
<div class="flex flex-wrap items-center gap-2 text-xs">
<div class="rounded-full bg-white px-3 py-1.5 font-medium text-primary shadow-sm">
{{ workspace.activeView === 'admin' ? `${$t('chat.training.hr.stats.passRate')} ${workspace.stats.passRate}%` : `${$t('chat.training.progressPercent')} ${workspace.learnerProgressPercent}%` }}
</div>
<div class="rounded-full bg-white px-3 py-1.5 font-medium text-primary shadow-sm">
{{ workspace.activeView === 'admin' ? `${$t('chat.training.hr.stats.total')} ${workspace.stats.total}` : `${$t('chat.training.result.scoreLabel')} ${workspace.score}` }}
</div>
</div>
</div>
</div>
<div v-if="!isCompactMode && workspace.activeView === 'learner'" class="grid gap-3 p-4 md:grid-cols-[minmax(0,1.25fr)_232px] md:p-5 lg:gap-4 lg:grid-cols-[minmax(0,1.4fr)_260px] 2xl:grid-cols-[minmax(0,1.55fr)_300px]">
<div class="min-w-0 space-y-4">
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-2.5 lg:flex-row lg:items-start lg:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.progressLabel') }}
</div>
<div class="mt-1 text-xs leading-5 text-secondary md:text-sm">
{{ $t('chat.training.progressHint') }}
</div>
</div>
<div class="rounded-xl bg-surface-soft px-3 py-2 text-center">
<div class="text-xs text-muted">{{ $t('chat.training.progressPercent') }}</div>
<div class="text-lg font-semibold leading-none text-primary">{{ workspace.learnerProgressPercent }}%</div>
</div>
</div>
<div class="mt-3 grid grid-cols-2 gap-2 lg:grid-cols-4">
<div
v-for="(item, index) in stageItems"
:key="item.key"
class="rounded-xl border px-3 py-2.5 transition cursor-pointer hover:border-brand-300"
:class="stageStep >= index + 1 ? 'border-brand-200 bg-brand-50/70' : 'border-default bg-surface-soft/70'"
@click="workspace.stage = item.key as any"
>
<div class="flex items-center gap-2">
<div
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg"
:class="stageStep >= index + 1 ? 'bg-brand-600 text-white' : 'bg-white text-muted'"
>
<component :is="item.icon" class="h-4 w-4" />
</div>
<div class="min-w-0">
<div class="text-[11px] font-semibold uppercase tracking-[0.16em] text-muted">
{{ String(index + 1).padStart(2, '0') }}
</div>
<div class="whitespace-normal text-sm font-medium leading-5 text-primary">{{ $t(item.label) }}</div>
</div>
</div>
</div>
</div>
</div>
<div v-if="workspace.stage === 'video'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<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>
</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" />
<div class="relative z-10 flex flex-col items-center gap-3">
<div class="h-16 w-16 flex items-center justify-center rounded-full bg-white/20 backdrop-blur-md border border-white/30 group-hover:bg-brand-600 group-hover:border-brand-500 transition-all duration-300">
<PlayCircle class="h-8 w-8 text-white fill-white/20" />
</div>
<span class="text-white font-medium drop-shadow-md">{{ $t('chat.training.video.playerTitle') }}</span>
</div>
</div>
</div>
<div v-else-if="workspace.stage === 'summary'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div>
<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>
<div class="mt-3 grid gap-3 md:grid-cols-2">
<div class="rounded-2xl border border-brand-100 bg-brand-50/50 p-3.5">
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.summary.keyPoints') }}</div>
<ul class="mt-2.5 space-y-1.5 text-sm leading-6 text-secondary">
<li v-for="point in workspace.summaryPoints" :key="point" class="flex gap-2">
<span class="mt-1.5 h-1.5 w-1.5 rounded-full bg-brand-500" />
<span>{{ point }}</span>
</li>
</ul>
</div>
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.summary.mustKnow') }}</div>
<ul class="mt-2.5 space-y-1.5 text-sm leading-6 text-secondary">
<li v-for="point in workspace.summaryChecklist" :key="point" class="flex gap-2">
<CheckCircle2 class="mt-1 h-4 w-4 shrink-0 text-emerald-500" />
<span>{{ point }}</span>
</li>
</ul>
</div>
</div>
</div>
<div v-else-if="workspace.stage === 'exam' && workspace.currentQuestion" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.exam.title') }}
</div>
<h3 class="mt-1 text-lg font-semibold text-primary">
{{ $t('chat.training.exam.questionCounter', { current: workspace.answeredCount + 1, total: workspace.totalQuestionCount }) }}
</h3>
</div>
<div class="flex flex-wrap gap-2 text-sm text-secondary">
<div class="rounded-xl bg-surface-soft px-3 py-1.5">
{{ $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') }}
</div>
</div>
</div>
<div class="mt-4 rounded-2xl border border-brand-100 bg-brand-50/40 p-3.5">
<div class="text-base font-semibold leading-7 text-primary">
{{ workspace.currentQuestion.prompt }}
</div>
</div>
<div class="mt-3 grid gap-2.5">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
type="button"
class="rounded-2xl border px-4 py-2.5 text-left text-sm transition"
:class="[
workspace.selectedOptionId === option.id
? workspace.answerLocked
? option.id === workspace.currentQuestion.answer
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
: 'border-red-300 bg-red-50 text-red-700'
: 'border-brand-300 bg-brand-50 text-brand-700'
: workspace.answerLocked && option.id === workspace.currentQuestion.answer
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
: 'border-default bg-white text-secondary hover:border-brand-200 hover:bg-brand-50/40',
]"
:disabled="workspace.answerLocked"
@click="workspace.selectAnswer(option.id)"
>
<div class="flex items-start justify-between gap-3">
<span>{{ option.label }}</span>
<CheckCircle2
v-if="workspace.answerLocked && option.id === workspace.currentQuestion.answer"
class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500"
/>
</div>
</button>
</div>
<div
v-if="workspace.answerLocked"
class="mt-4 rounded-2xl border p-3.5"
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
>
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="workspace.currentFeedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.selectedAnswer', { answer: currentAnswerLabel || '--' }) }}
</div>
<div class="mt-1 text-sm leading-6 text-secondary">
{{ $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.options?.find((item) => item.id === workspace.currentQuestion?.answer)?.label || '--' }) }}
</div>
<div class="mt-2 text-sm leading-6 text-secondary">
{{ workspace.currentQuestion.explanation }}
</div>
<div class="mt-3">
<button
type="button"
class="inline-flex items-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.moveToNextQuestion"
>
<ClipboardCheck class="h-4 w-4" />
{{
workspace.answeredCount >= workspace.totalQuestionCount
? $t('chat.training.exam.finishExam')
: $t('chat.training.exam.nextQuestion')
}}
</button>
</div>
</div>
</div>
<div v-else class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
<div class="inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs font-semibold"
:class="workspace.isPassed ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
>
<ShieldCheck class="h-3.5 w-3.5" />
{{ workspace.isPassed ? $t('chat.training.result.passedTag') : $t('chat.training.result.failedTag') }}
</div>
<h3 class="mt-2.5 text-lg font-semibold text-primary md:text-xl">
{{ 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') }}
</p>
</div>
<div class="grid grid-cols-2 gap-2 text-center">
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.scoreLabel') }}</div>
<div class="text-xl font-semibold text-primary">{{ workspace.score }}</div>
</div>
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.attemptsLabel') }}</div>
<div class="text-xl font-semibold text-primary">{{ workspace.attemptCount }}</div>
</div>
</div>
</div>
<div class="mt-3 grid gap-2.5 md:grid-cols-3">
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.correctCount') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.correctCount }}</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.wrongCount') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.wrongCount }}</div>
</div>
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
<div class="text-xs text-muted">{{ $t('chat.training.result.completionDate') }}</div>
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.completionDate || '--' }}</div>
</div>
</div>
<div class="mt-4 flex flex-wrap gap-2.5">
<button
v-if="!workspace.isPassed"
type="button"
class="inline-flex items-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.restartExam"
>
<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>
<div class="min-w-0 md:sticky md:top-4 md:self-start">
<div class="rounded-2xl border border-default bg-white p-3 shadow-sm">
<div class="flex items-center gap-2">
<Users class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.learnerCard.title') }}</div>
</div>
<div class="mt-2.5 grid gap-1.5 text-sm text-secondary">
<div class="flex items-center justify-between rounded-xl bg-surface-soft px-3 py-2">
<span>{{ $t('chat.training.learnerCard.name') }}</span>
<span class="font-medium text-primary">{{ workspace.currentUserName }}</span>
</div>
<div class="flex items-center justify-between rounded-xl bg-surface-soft px-3 py-2">
<span>{{ $t('chat.training.learnerCard.employeeId') }}</span>
<span class="font-medium text-primary">{{ workspace.currentUserEmployeeId }}</span>
</div>
<div class="flex items-center justify-between rounded-xl bg-surface-soft px-3 py-2">
<span>{{ $t('chat.training.learnerCard.department') }}</span>
<span class="font-medium text-primary">{{ workspace.currentUserDepartment }}</span>
</div>
</div>
<div class="my-3 h-px bg-slate-100" />
<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">
<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>
</li>
</ul>
</div>
</div>
</div>
<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>
<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>
<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>
<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>
<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>
</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>
<input
v-model="workspace.hrKeyword"
type="text"
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"
: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>
<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"
>
<option value="all">{{ $t('chat.training.hr.filters.allStatuses') }}</option>
<option value="passed">{{ $t('chat.training.hr.status.passed') }}</option>
<option value="failed">{{ $t('chat.training.hr.status.failed') }}</option>
<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>
<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"
>
<option value="all">{{ $t('chat.training.hr.filters.allDepartments') }}</option>
<option v-for="department in workspace.departmentOptions" :key="department" :value="department">
{{ department }}
</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>
<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"
@click="workspace.exportRecords"
>
<Download class="h-4 w-4" />
{{ $t('chat.training.hr.actions.export') }}
</button>
</div>
</div>
<div class="mt-4 overflow-x-auto rounded-2xl border border-default">
<table class="min-w-full border-collapse text-sm">
<thead class="bg-surface-soft">
<tr>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.joinDate') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.completionDate') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.department') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.name') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.employeeId') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.score') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.attempts') }}</th>
<th class="border-b border-default px-3 py-2.5 text-left font-semibold text-primary">{{ $t('chat.training.hr.columns.status') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="record in workspace.filteredRecords" :key="record.id" class="odd:bg-white even:bg-surface-soft/30">
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.joinDate }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.completionDate || '--' }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.department }}</td>
<td class="border-b border-default px-3 py-2.5 font-medium text-primary">{{ record.name }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.employeeId }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.score ?? '--' }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.attempts }}</td>
<td class="border-b border-default px-3 py-2.5">
<span
class="inline-flex rounded-full px-2.5 py-1 text-xs font-semibold"
:class="record.status === 'passed'
? 'bg-emerald-50 text-emerald-700'
: record.status === 'failed'
? 'bg-amber-50 text-amber-700'
: 'bg-blue-50 text-blue-700'"
>
{{ $t(`chat.training.hr.status.${record.status}`) }}
</span>
</td>
</tr>
<tr v-if="workspace.filteredRecords.length === 0">
<td colspan="8" class="px-4 py-6 text-center text-sm text-muted">
{{ $t('chat.training.hr.empty') }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<Teleport to="body">
<div v-if="showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="showVideoModal = false">
<div class="relative w-full max-w-4xl overflow-hidden rounded-3xl bg-black shadow-2xl">
<button @click="showVideoModal = false" class="absolute top-4 right-4 z-10 h-10 w-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition backdrop-blur-md">
<XCircle class="h-6 w-6" />
</button>
<div class="aspect-video bg-black">
<video
controls
autoplay
class="h-full w-full"
@timeupdate="handleVideoTimeUpdate"
@seeking="handleVideoSeeking"
@ended="handleVideoEnded"
>
<source :src="workspace.videoUrl" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
</div>
</Teleport>
</template>
@@ -11,6 +11,10 @@ import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBloc
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
import TrainingExamQuestionMessage, { type TrainingHandlers } from './TrainingExamQuestionMessage.vue';
import TrainingVideoMessage from './TrainingVideoMessage.vue';
import TrainingSummaryMessage from './TrainingSummaryMessage.vue';
import TrainingResultCard from './TrainingResultCard.vue';
import type { ChatMessage, InlineDownloadFile, SourceFileLink } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
@@ -57,6 +61,7 @@ const {
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
trainingHandlers: TrainingHandlers;
}>();
const emit = defineEmits<{
@@ -73,6 +78,35 @@ const isLeaveMessage = computed(() =>
|| message.type === 'leave-result',
);
const isTrainingExamMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 必须是最后一条助手消息,且包含题目特征文字(确保只在当前正在进行的题目上显示交互组件)
if (!isLastMessage.value) return false;
const content = message.content || '';
return content.includes('正在进行新人培训考试')
|| (content.includes('第') && content.includes('题') && (content.includes('共') || content.includes('/')));
});
const isTrainingVideoMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要包含特定引导文案,就显示视频占位符,不限于最后一条消息
const content = message.content || '';
return content.includes('专属入职培训助手') || (content.includes('看视频') && content.includes('已看完'));
});
const isTrainingSummaryMessage = computed(() => {
if (message.role !== 'assistant') return false;
const content = message.content || '';
return content.includes('完成视频学习') || content.includes('复盘重点知识') || content.includes('复盘知识点') || content.includes('总结重点知识');
});
const isTrainingResultMessage = computed(() => {
if (message.role !== 'assistant') return false;
// 只要是结果文案,就显示结算卡片,不限于最后一条消息
const content = message.content || '';
return content.includes('考试结束') || content.includes('顺利通过新人考核');
});
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
const sourceLinks = computed(() => handlers.getSourceLinks(retrieverResources.value));
@@ -480,13 +514,51 @@ function handleInlineDownload(file: InlineDownloadFile): void {
:action-button-class="handlers.shippingActionButtonClass"
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
/>
<TrainingExamQuestionMessage
v-else-if="isTrainingExamMessage && trainingHandlers.getQuestion()"
:question="trainingHandlers.getQuestion()!"
:current-question-index="trainingHandlers.getCurrentQuestionIndex()"
:answered-count="trainingHandlers.getAnsweredCount()"
:total-count="trainingHandlers.getTotalCount()"
:score="trainingHandlers.getScore()"
:selected-option-id="trainingHandlers.getSelectedOptionId()"
:answer-locked="trainingHandlers.getAnswerLocked()"
:feedback-correct="trainingHandlers.getFeedbackCorrect()"
:answer-label="trainingHandlers.getAnswerLabel()"
:is-thinking="isThinking"
@select="trainingHandlers.onSelect"
@next="trainingHandlers.onNext"
/>
<TrainingResultCard
v-else-if="isTrainingResultMessage"
:score="trainingHandlers.getScore()"
:is-passed="trainingHandlers.getScore() >= 90"
:correct-count="trainingHandlers.getCorrectCount()"
:wrong-count="trainingHandlers.getWrongCount()"
:is-thinking="isThinking"
@restart="trainingHandlers.onRestartExam"
/>
<div
v-else-if="renderedMarkdown"
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
@click="handlers.onMarkdownClick"
ref="markdownContainer"
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
v-html="renderedMarkdown"
/>
<TrainingVideoMessage
v-if="isTrainingVideoMessage"
:is-thinking="isThinking"
@play="trainingHandlers.onPlayVideo"
/>
<TrainingSummaryMessage
v-if="isTrainingSummaryMessage"
:summary-points="trainingHandlers.getSummaryPoints()"
:summary-checklist="trainingHandlers.getSummaryChecklist()"
:is-thinking="isThinking"
@start-exam="trainingHandlers.onStartExam"
/>
<div v-if="actionableInlineFileEntries.length > 0" class="mt-4">
<div class="flex flex-wrap gap-2">
<button
@@ -0,0 +1,151 @@
/**
* features/chat/components/messages/TrainingExamQuestionMessage.vue
* 用途:在聊天气泡中渲染交互式答题选择器,支持单选题与判断题。
* 逻辑:由 ChatMessageBubble 内部调用;展示当前题目内容、选项,并在答题后展示即时反馈与“下一题”操作。
*/
<script setup lang="ts">
import { CheckCircle2, XCircle, ClipboardCheck } from 'lucide-vue-next';
import type { TrainingQuestion } from '@/features/chat/training/training.types';
export interface TrainingHandlers {
getQuestion: () => TrainingQuestion | null;
getCurrentQuestionIndex: () => number;
getAnsweredCount: () => number;
getTotalCount: () => number;
getScore: () => number;
getSelectedOptionId: () => string;
getAnswerLocked: () => boolean;
getFeedbackCorrect: () => boolean;
getAnswerLabel: () => string;
onSelect: (optionId: string) => void;
onNext: () => void;
onPlayVideo: () => void;
onStartExam: () => void;
onRestartExam: () => void;
getCorrectCount: () => number;
getWrongCount: () => number;
getSummaryPoints: () => string[];
getSummaryChecklist: () => string[];
}
const props = defineProps<{
question: TrainingQuestion;
currentQuestionIndex: number;
answeredCount: number;
totalCount: number;
score: number;
selectedOptionId: string;
answerLocked: boolean;
feedbackCorrect: boolean;
answerLabel: string;
isThinking: boolean;
}>();
const emit = defineEmits<{
select: [optionId: string];
next: [];
}>();
const passLine = 90;
</script>
<template>
<div class="my-2 flex flex-col gap-4 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm ring-1 ring-brand-50/50">
<!-- 头部进度与分数 -->
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<div class="text-[11px] font-bold uppercase tracking-[0.15em] text-brand-600/80">
第三步:逐题考试
</div>
<h3 class="mt-1 text-lg font-bold text-slate-800">
第 {{ currentQuestionIndex + 1 }} / {{ totalCount }} 题
</h3>
</div>
<div class="flex flex-wrap gap-2 text-[13px]">
<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">{{ score }} 分</span>
</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>
</div>
</div>
</div>
<!-- 题目正文 -->
<div class="rounded-xl bg-brand-50/30 p-4 border border-brand-100/50">
<div class="text-[15px] font-bold leading-7 text-slate-800">
{{ question.prompt }}
</div>
</div>
<!-- 选项列表 -->
<div class="grid gap-2.5">
<button
v-for="option in question.options"
:key="option.id"
type="button"
class="group relative flex items-center justify-between rounded-2xl border px-5 py-3.5 text-left text-[14px] transition-all duration-200"
:class="[
selectedOptionId === option.id
? answerLocked
? option.id === question.answer
? 'border-emerald-300 bg-emerald-50 text-emerald-700 ring-4 ring-emerald-500/5'
: 'border-red-300 bg-red-50 text-red-700 ring-4 ring-red-500/5'
: 'border-brand-300 bg-brand-50 text-brand-700 ring-4 ring-brand-500/5'
: answerLocked && option.id === question.answer
? 'border-emerald-200 bg-emerald-50/50 text-emerald-600'
: 'border-slate-200 bg-white text-slate-600 hover:border-brand-200 hover:bg-brand-50/30 hover:text-brand-700',
]"
:disabled="answerLocked || isThinking"
@click="emit('select', option.id)"
>
<span class="font-medium">{{ option.label }}</span>
<CheckCircle2
v-if="answerLocked && option.id === question.answer"
class="h-5 w-5 shrink-0 text-emerald-500"
/>
</button>
</div>
<!-- 答题反馈 -->
<div
v-if="answerLocked"
class="mt-1 animate-in fade-in slide-in-from-top-2 duration-300 rounded-2xl border p-4"
:class="feedbackCorrect ? 'border-emerald-100 bg-emerald-50/60' : 'border-red-100 bg-red-50/60'"
>
<div class="flex items-center gap-2 text-sm font-bold" :class="feedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
<CheckCircle2 v-if="feedbackCorrect" class="h-4 w-4" />
<XCircle v-else class="h-4 w-4" />
{{ feedbackCorrect ? '回答正确,继续下一题' : '回答错误' }}
</div>
<div class="mt-3 space-y-2 text-[13px] leading-6 text-slate-600">
<div class="flex gap-2">
<span class="font-medium text-slate-500 shrink-0">你的答案:</span>
<span class="font-medium" :class="feedbackCorrect ? 'text-emerald-600' : 'text-red-600'">{{ answerLabel || '--' }}</span>
</div>
<div v-if="!feedbackCorrect" class="flex gap-2">
<span class="font-medium text-slate-500 shrink-0">正确答案:</span>
<span class="text-emerald-600 font-medium">{{ question.options?.find(o => o.id === question.answer)?.label || '--' }}</span>
</div>
<div class="mt-2 pl-2 border-l-2 border-slate-200/60 text-slate-500/90">
{{ question.explanation }}
</div>
</div>
<div class="mt-4">
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-5 py-2.5 text-[14px] font-bold text-white shadow-lg shadow-brand-500/20 transition-all hover:bg-brand-700 hover:-translate-y-0.5 active:translate-y-0 disabled:opacity-50 disabled:translate-y-0"
:disabled="isThinking"
@click="emit('next')"
>
<ClipboardCheck class="h-4 w-4" />
{{ answeredCount >= totalCount - 1 ? '完成考试并查看结果' : '下一题' }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,88 @@
/**
* features/chat/components/messages/TrainingResultCard.vue
* 用途:在聊天气泡中渲染考试结算结果。
*/
<script setup lang="ts">
import { ShieldCheck, XCircle, RotateCcw, CheckCircle2 } from 'lucide-vue-next';
defineProps<{
score: number;
isPassed: boolean;
correctCount: number;
wrongCount: number;
isThinking: boolean;
}>();
const emit = defineEmits<{
restart: [];
}>();
</script>
<template>
<div class="my-2 flex flex-col gap-5 rounded-2xl border border-brand-100 bg-white p-5 shadow-sm ring-1 ring-brand-50/50">
<!-- 状态头部 -->
<div class="flex items-center justify-between">
<div class="flex items-center gap-2.5">
<div
class="flex h-10 w-10 items-center justify-center rounded-xl"
:class="isPassed ? 'bg-emerald-100 text-emerald-600' : 'bg-red-100 text-red-600'"
>
<ShieldCheck v-if="isPassed" class="h-6 w-6" />
<XCircle v-else class="h-6 w-6" />
</div>
<div>
<div class="text-[11px] font-bold uppercase tracking-[0.15em] text-slate-500">
第四步:结算结果
</div>
<h3 class="text-lg font-bold text-slate-800">
{{ isPassed ? '恭喜,你已通过考核!' : '很遗憾,考试未通过' }}
</h3>
</div>
</div>
<div
class="rounded-full px-3 py-1 text-xs font-bold uppercase"
:class="isPassed ? 'bg-emerald-50 text-emerald-700 border border-emerald-100' : 'bg-red-50 text-red-700 border border-red-100'"
>
{{ isPassed ? 'PASSED' : 'FAILED' }}
</div>
</div>
<!-- 分数展示 -->
<div class="grid grid-cols-3 gap-3">
<div class="rounded-2xl bg-slate-50 p-4 border border-slate-100 text-center">
<div class="text-[11px] font-bold text-slate-400 uppercase">{{ $t('chat.training.result.scoreLabel') }}</div>
<div class="mt-1 text-2xl font-black text-brand-600">{{ score }}</div>
</div>
<div class="rounded-2xl bg-emerald-50/50 p-4 border border-emerald-100/50 text-center">
<div class="text-[11px] font-bold text-emerald-500 uppercase">{{ $t('chat.training.result.correctCount') }}</div>
<div class="mt-1 text-2xl font-black text-emerald-600">{{ correctCount }}</div>
</div>
<div class="rounded-2xl bg-red-50/50 p-4 border border-red-100/50 text-center">
<div class="text-[11px] font-bold text-red-400 uppercase">答错</div>
<div class="mt-1 text-2xl font-black text-red-500">{{ wrongCount }}</div>
</div>
</div>
<!-- 描述语 -->
<div class="text-sm leading-relaxed text-slate-600">
{{ isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription') }}
</div>
<!-- 操作 -->
<div v-if="!isPassed" class="pt-2">
<button
type="button"
class="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-slate-800 px-5 py-3 text-sm font-bold text-white transition-all hover:bg-slate-900 active:scale-[0.98] disabled:opacity-50"
:disabled="isThinking"
@click="emit('restart')"
>
<RotateCcw class="h-4 w-4" />
重新考试
</button>
</div>
<div v-else class="flex items-center gap-2 text-emerald-600 font-medium text-sm">
<CheckCircle2 class="h-4 w-4" />
成绩已同步至 HR 管理系统
</div>
</div>
</template>
@@ -0,0 +1,87 @@
/**
* features/chat/components/messages/TrainingSummaryMessage.vue
* 用途:在聊天气泡中渲染“知识点复盘”卡片。
* 逻辑:展示重点知识和考前必知,并提供“开始考试”按钮。
*/
<script setup lang="ts">
import { BookOpen, CheckCircle2, ClipboardCheck } from 'lucide-vue-next';
defineProps<{
summaryPoints: string[];
summaryChecklist: string[];
isThinking: boolean;
}>();
const emit = defineEmits<{
startExam: [];
}>();
</script>
<template>
<div class="my-2 flex flex-col gap-4 rounded-2xl border border-brand-100 bg-white p-4 shadow-sm ring-1 ring-brand-50/50">
<!-- 头部 -->
<div class="flex flex-col gap-1 sm:flex-row sm:items-center sm:justify-between">
<div class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
<BookOpen class="h-5 w-5" />
</div>
<div>
<h3 class="text-base font-bold text-slate-800">
{{ $t('chat.training.summary.title') }}
</h3>
<p class="text-[12px] text-slate-500">
{{ $t('chat.training.summary.description') }}
</p>
</div>
</div>
<button
type="button"
class="mt-2 inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-[13px] font-bold text-white shadow-md shadow-brand-500/20 transition-all hover:bg-brand-700 sm:mt-0"
:disabled="isThinking"
@click="emit('startExam')"
>
<ClipboardCheck class="h-4 w-4" />
{{ $t('chat.training.summary.startExam') }}
</button>
</div>
<!-- 内容网格 -->
<div class="grid gap-4 md:grid-cols-2">
<!-- 重点知识 -->
<div class="rounded-xl bg-brand-50/30 p-4 border border-brand-100/50">
<h4 class="mb-3 flex items-center gap-2 text-[14px] font-bold text-brand-700">
<div class="h-1.5 w-1.5 rounded-full bg-brand-500"></div>
{{ $t('chat.training.summary.keyPoints') }}
</h4>
<ul class="space-y-2.5">
<li
v-for="(point, i) in summaryPoints"
:key="i"
class="flex gap-2 text-[13px] leading-6 text-slate-600"
>
<span class="text-brand-400 font-bold">•</span>
<span>{{ point }}</span>
</li>
</ul>
</div>
<!-- 考前必知 -->
<div class="rounded-xl bg-slate-50/50 p-4 border border-slate-100">
<h4 class="mb-3 flex items-center gap-2 text-[14px] font-bold text-slate-700">
<div class="h-1.5 w-1.5 rounded-full bg-slate-400"></div>
{{ $t('chat.training.summary.mustKnow') }}
</h4>
<ul class="space-y-2.5">
<li
v-for="(item, i) in summaryChecklist"
:key="i"
class="flex gap-2 text-[13px] leading-6 text-slate-600"
>
<CheckCircle2 class="mt-1 h-3.5 w-3.5 shrink-0 text-emerald-500/80" />
<span>{{ item }}</span>
</li>
</ul>
</div>
</div>
</div>
</template>
@@ -0,0 +1,37 @@
/**
* features/chat/components/messages/TrainingVideoMessage.vue
* 用途:在聊天气泡中渲染培训视频占位符。
* 逻辑:点击占位符触发视频播放弹窗(复用工作区逻辑)。
*/
<script setup lang="ts">
import { PlayCircle } from 'lucide-vue-next';
defineProps<{
isThinking: boolean;
}>();
const emit = defineEmits<{
play: [];
}>();
</script>
<template>
<div class="my-1.5 flex flex-col gap-3 rounded-2xl border border-brand-100 bg-white p-3 shadow-sm ring-1 ring-brand-50/30">
<div
class="relative group cursor-pointer overflow-hidden rounded-xl border border-default bg-slate-900 shadow-sm aspect-video flex items-center justify-center"
:class="{ 'opacity-50 pointer-events-none': isThinking }"
@click="emit('play')"
>
<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"
/>
<div class="relative z-10 flex flex-col items-center gap-2">
<div class="h-12 w-12 flex items-center justify-center rounded-full bg-white/20 backdrop-blur-md border border-white/30 group-hover:bg-brand-600 group-hover:border-brand-500 transition-all duration-300">
<PlayCircle class="h-6 w-6 text-white fill-white/20" />
</div>
<span class="text-white text-xs font-medium drop-shadow-md">点击播放视频</span>
</div>
</div>
</div>
</template>
@@ -18,6 +18,9 @@ export type AgentSuggestedQuestionItem = {
const DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
const isTrainingAgentName = (name: string) => TRAINING_AGENT_NAME_PATTERN.test(name);
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
@@ -48,6 +51,15 @@ const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styl
},
};
const TRAINING_AGENT_DESCRIPTION = '我是你的新人培训助手,会在同一个聊天页面内带你完成视频学习、知识点复盘、逐题考试和结果复盘。';
const TRAINING_AGENT_QUESTIONS: AgentSuggestedQuestionItem[] = [
{ question: '开始新人培训', group: '培训流程' },
{ question: '我已看完视频,请总结知识点', group: '培训流程' },
{ question: '开始考试', group: '培训流程' },
{ question: '导出本月培训成绩', group: 'HR 管理' },
];
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
@@ -118,6 +130,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
const agentDescription = computed(() => {
const text = String(currentAgent.value?.description || '').trim();
if (!text && isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_DESCRIPTION;
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
});
@@ -125,6 +138,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
if (isTrainingAgentName(currentAgentName.value)) return 'styled';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
});
@@ -133,6 +147,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
);
if (configured.length > 0) return configured;
if (isTrainingAgentName(currentAgentName.value)) return TRAINING_AGENT_QUESTIONS;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
});
@@ -2,7 +2,7 @@
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
*/
import { computed, markRaw, ref, watch } from 'vue';
import { computed, markRaw, nextTick, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
@@ -26,6 +26,7 @@ import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatStore } from '../stores/chat.store';
import { useTrainingWorkspace, matchesTrainingAgent } from './useTrainingWorkspace';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
@@ -34,6 +35,7 @@ import {
createLeaveMessageHandlers,
createShippingMappingHandlers,
createShippingPickerRefHolder,
createTrainingHandlers,
useChatPageDialogs,
useChatPageUser,
useChatPageVoice,
@@ -212,6 +214,34 @@ export function useChatPage() {
currentAgentId,
});
const pushLocalAssistantMessage = async (content: string) => {
const msgText = String(content || '').trim();
if (!msgText) return;
const isFirstMessage = messages.value.length === 0;
const isTraining = matchesTrainingAgent(agent.currentAgent.value);
// 如果是培训 Agent 的首条消息(欢迎语),强制重置滚动贴底状态,防止自动滚到底部
if (isFirstMessage && isTraining) {
scroll.isNearBottom.value = false;
}
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: msgText,
local_id: newLocalMessageId('local-assistant'),
local_only: true,
};
messages.value.push(assistantMsg);
await saveLocalMessageToBackend(assistantMsg);
// 再次确保滚到顶部展示欢迎语
if (isFirstMessage && isTraining) {
await nextTick();
scroll.scrollToTop();
}
};
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
@@ -286,6 +316,27 @@ export function useChatPage() {
t,
});
const pushLocalUserMessage = async (content: string) => {
const msgText = String(content || '').trim();
if (!msgText) return;
const userMsg: ChatMessage = {
role: 'user',
type: 'text',
content: msgText,
local_id: newLocalMessageId('local-user'),
local_only: true,
};
messages.value.push(userMsg);
await saveLocalMessageToBackend(userMsg);
};
const training = useTrainingWorkspace({
currentAgent: computed(() => agent.currentAgent.value),
currentUser: computed(() => currentUser.value),
pushLocalAssistantMessage,
pushLocalUserMessage,
});
const markdown = createChatPageMarkdownApi({
messages,
isThinking,
@@ -361,6 +412,7 @@ export function useChatPage() {
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
const trainingHandlers = createTrainingHandlers(training);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const shippingNoticePickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingNoticePickerRef));
@@ -452,9 +504,11 @@ export function useChatPage() {
isVoiceRecording: voice.isVoiceRecording,
isVoiceTranscribing: voice.isVoiceTranscribing,
handleVoiceFeatureClick: voice.handleVoiceFeatureClick,
training,
...leave,
leaveMessageHandlers,
shippingMappingHandlers,
trainingHandlers,
shippingPickerRefHolder,
shippingNoticePickerRefHolder,
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
@@ -462,6 +516,7 @@ export function useChatPage() {
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
handleSend: sendApi.handleSend,
pushLocalAssistantMessage,
copyToClipboard: sendApi.copyToClipboard,
regenerate: sendApi.regenerate,
handleOpenFeedback: dialogs.handleOpenFeedback,
@@ -66,6 +66,17 @@ export function useChatScroll(options: UseChatScrollOptions) {
});
};
const scrollToTop = async () => {
await nextTick();
const el = container.value;
if (!el) return;
el.scrollTo({
top: 0,
behavior: 'auto',
});
isNearBottom.value = false;
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
@@ -139,6 +150,7 @@ export function useChatScroll(options: UseChatScrollOptions) {
showScrollToBottom,
scrollToBottom,
scrollToBottomSmooth,
scrollToTop,
scrollToUserQuestion,
scheduleScrollToBottom,
setupThinkingScrollWatch,
@@ -0,0 +1,480 @@
/**
* features/chat/composables/useTrainingWorkspace.ts
* 用途:封装新人培训 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 {
exportTrainingRecords,
getMyTrainingProgress,
getTrainingStats,
listTrainingRecords,
saveMyTrainingProgress,
} from '@/features/chat/api/training.api';
import type {
TrainingAnswerRecord,
TrainingQuestion,
TrainingQuestionOption,
TrainingProgressRecord,
TrainingRecord,
TrainingRecordStatus,
TrainingStage,
TrainingStats,
TrainingWorkspaceView,
} from '@/features/chat/training/training.types';
type TrainingAgentLike = {
name?: string | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
type TrainingUserLike = {
role?: string | null;
username?: string | null;
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
} | null | undefined;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
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 formatDate = (value: Date) => value.toISOString().slice(0, 10);
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
const { t, tm } = useI18n();
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
const activeView = ref<TrainingWorkspaceView>('learner');
const stage = ref<TrainingStage>('video');
const currentQuestionIndex = ref(0);
const score = ref(0);
const attemptCount = ref(0);
const selectedOptionId = ref('');
const answerLocked = ref(false);
const currentFeedbackCorrect = ref(false);
const answerRecords = ref<TrainingAnswerRecord[]>([]);
const completionDate = ref<string | null>(null);
const currentJoinDate = ref<string | null>(null);
const isHydrated = ref(false);
const hrKeyword = ref('');
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
const hrDepartmentFilter = ref('all');
const records = ref<TrainingRecord[]>([]);
const departmentOptions = ref<string[]>([]);
const stats = ref<TrainingStats>({
total: 0,
passed: 0,
failed: 0,
inProgress: 0,
passRate: 0,
averageScore: 0,
});
let persistQueue: Promise<void> = Promise.resolve();
watch(isTrainingAgent, (enabled) => {
if (!enabled) {
activeView.value = 'learner';
isHydrated.value = false;
}
});
const summaryPoints = computed(() => {
const raw = tm('chat.training.summaryPoints');
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
});
const summaryChecklist = computed(() => {
const raw = tm('chat.training.summaryChecklist');
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
});
const rawQuestionBank = computed(() => {
const raw = tm('chat.training.questionBank');
return Array.isArray(raw) ? raw as Array<Record<string, unknown>> : [];
});
const booleanOptions = computed<TrainingQuestionOption[]>(() => {
const raw = tm('chat.training.booleanOptions');
if (!Array.isArray(raw)) return [];
return raw.map((item) => ({
id: String((item as Record<string, unknown>).id || ''),
label: String((item as Record<string, unknown>).label || ''),
}));
});
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
const type = String(item.type || 'single') as TrainingQuestion['type'];
const rawOptions = Array.isArray(item.options) ? item.options : [];
const options = type === 'boolean'
? booleanOptions.value
: rawOptions.map((option) => ({
id: String((option as Record<string, unknown>).id || ''),
label: String((option as Record<string, unknown>).label || ''),
}));
return {
id: String(item.id || ''),
type,
prompt: String(item.prompt || ''),
answer: String(item.answer || ''),
explanation: String(item.explanation || ''),
options,
};
}));
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 learnerProgressPercent = computed(() => {
if (stage.value === 'video') return 25;
if (stage.value === 'summary') return 50;
if (stage.value === 'result') return 100;
const base = 50;
const examProgress = totalQuestionCount.value > 0
? Math.round((answeredCount.value / totalQuestionCount.value) * 50)
: 0;
return Math.min(100, base + examProgress);
});
const currentUserName = computed(() => (
String(currentUser.value?.real_name || '').trim()
|| String(currentUser.value?.username || '').trim()
|| t('chat.training.defaultLearnerName')
));
const currentUserEmployeeId = computed(() => String(currentUser.value?.employee_id || '').trim() || '--');
const currentUserDepartment = computed(() => String(currentUser.value?.department || '').trim() || t('chat.training.unknownDepartment'));
const filteredRecords = computed(() => records.value);
/**
* 重置考试状态,为首次开考或再次补考共用。
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
*/
const resetExamState = () => {
currentQuestionIndex.value = 0;
score.value = 0;
selectedOptionId.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
answerRecords.value = [];
completionDate.value = null;
};
const syncAnswerStateForCurrentQuestion = () => {
const questionId = currentQuestion.value?.id;
const currentAnswer = questionId
? answerRecords.value.find((item) => item.questionId === questionId)
: null;
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
answerLocked.value = Boolean(currentAnswer);
currentFeedbackCorrect.value = Boolean(currentAnswer?.correct);
};
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
if (!record) {
stage.value = 'video';
resetExamState();
currentJoinDate.value = null;
return;
}
stage.value = record.stage;
currentQuestionIndex.value = record.currentQuestionIndex;
score.value = Number(record.score || 0);
attemptCount.value = Number(record.attempts || 0);
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
completionDate.value = record.completionDate;
currentJoinDate.value = record.joinDate || null;
syncAnswerStateForCurrentQuestion();
};
const buildProgressPayload = () => ({
stage: stage.value,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
attemptCount: attemptCount.value,
answerDetails: answerRecords.value,
joinDate: currentJoinDate.value || formatDate(new Date()),
});
const persistProgress = async () => {
if (!isTrainingAgent.value) return;
persistQueue = persistQueue.catch(() => undefined).then(async () => {
try {
const saved = await saveMyTrainingProgress(buildProgressPayload());
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
if (isAdminViewer.value) {
void loadAdminRecords();
}
} catch {
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
}
});
await persistQueue;
};
const loadTrainingProgress = async () => {
if (!isTrainingAgent.value) return;
try {
const record = await getMyTrainingProgress();
applyProgressRecord(record);
} catch {
applyProgressRecord(null);
} finally {
isHydrated.value = true;
}
};
const loadAdminRecords = async () => {
if (!isTrainingAgent.value || !isAdminViewer.value) return;
try {
const query = {
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
};
const [recordData, statsData] = await Promise.all([
listTrainingRecords(query),
getTrainingStats(query),
]);
records.value = recordData.items;
departmentOptions.value = recordData.departmentOptions;
stats.value = statsData;
} catch {
records.value = [];
departmentOptions.value = [];
stats.value = {
total: 0,
passed: 0,
failed: 0,
inProgress: 0,
passRate: 0,
averageScore: 0,
};
}
};
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(
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
([enabled, canView]) => {
if (!enabled || !canView) return;
void loadAdminRecords();
},
{ immediate: true },
);
const markVideoCompleted = () => {
stage.value = 'summary';
// 立即推入本地助手消息(复盘卡片)
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
};
const startExam = () => {
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
// 立即推入第一题的消息引导
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
};
const selectAnswer = (optionId: string) => {
if (answerLocked.value || !currentQuestion.value) return;
selectedOptionId.value = optionId;
const isCorrect = optionId === currentQuestion.value.answer;
currentFeedbackCorrect.value = isCorrect;
if (isCorrect) {
score.value += 5;
}
answerRecords.value.push({
questionId: currentQuestion.value.id,
selectedOptionId: optionId,
correct: isCorrect,
});
answerLocked.value = true;
// 推入用户选择的答案到聊天流
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
void pushLocalUserMessage?.(label);
void persistProgress();
};
/**
* 进入下一题或结束考试。
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
*/
const moveToNextQuestion = () => {
if (!answerLocked.value) return;
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
stage.value = 'result';
completionDate.value = formatDate(new Date());
// 推入结果消息
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
return;
}
currentQuestionIndex.value += 1;
selectedOptionId.value = '';
answerLocked.value = false;
currentFeedbackCorrect.value = false;
// 推入下一题消息
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
};
const restartExam = () => {
stage.value = 'summary';
resetExamState();
// 重新推回复盘卡片
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
void persistProgress();
};
const exportRecords = async () => {
await exportTrainingRecords({
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
});
};
const managementChatPrompt = computed(() => {
const parts = [
t('chat.training.chatPrompts.hrSummaryPrefix'),
`${t('chat.training.hr.filters.keywordLabel')}: ${hrKeyword.value || t('chat.training.hr.filters.noLimit')}`,
`${t('chat.training.hr.filters.statusLabel')}: ${hrStatusFilter.value === 'all' ? t('chat.training.hr.filters.allStatuses') : t(`chat.training.hr.status.${hrStatusFilter.value}`)}`,
`${t('chat.training.hr.filters.departmentLabel')}: ${hrDepartmentFilter.value === 'all' ? t('chat.training.hr.filters.allDepartments') : hrDepartmentFilter.value}`,
`${t('chat.training.hr.stats.passRate')}: ${stats.value.passRate}%`,
];
return parts.join(';');
});
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:结算
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,
question: currentQuestion.value?.prompt || '',
});
});
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;
});
return {
isTrainingAgent,
isAdminViewer,
isHydrated,
activeView,
stage,
currentQuestionIndex,
currentQuestion,
totalQuestionCount,
answeredCount,
score,
attemptCount,
selectedOptionId,
answerLocked,
currentFeedbackCorrect,
answerRecords,
completionDate,
summaryPoints,
summaryChecklist,
learnerProgressPercent,
correctCount,
wrongCount,
isPassed,
currentUserName,
currentUserEmployeeId,
currentUserDepartment,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
departmentOptions,
filteredRecords,
stats,
learnerChatPrompt,
managementChatPrompt,
markVideoCompleted,
startExam,
selectAnswer,
moveToNextQuestion,
restartExam,
exportRecords,
showVideoModal,
videoUrl,
};
}
@@ -3,8 +3,10 @@
*/
import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from '../components/messages/ShippingInventoryMappingMessage.vue';
import type { TrainingHandlers } from '../components/messages/TrainingExamQuestionMessage.vue';
import type { useChatLeave } from '../composables/useChatLeave';
import type { useChatShipping } from '../composables/useChatShipping';
import type { useTrainingWorkspace } from '../composables/useTrainingWorkspace';
import type { Ref } from 'vue';
type LeaveHandlerSource = Pick<
@@ -41,6 +43,8 @@ type ShippingHandlerSource = Pick<
| 'removeShippingParseReviewLine'
>;
type TrainingHandlerSource = ReturnType<typeof useTrainingWorkspace>;
/** 请假消息块 handlers(LeaveMessageBlock) */
export function createLeaveMessageHandlers(leave: LeaveHandlerSource): LeaveMessageHandlers {
return {
@@ -81,6 +85,38 @@ export function createShippingMappingHandlers(shipping: ShippingHandlerSource):
};
}
/** 培训答题块 handlers(TrainingExamQuestionMessage) */
export function createTrainingHandlers(workspace: TrainingHandlerSource): TrainingHandlers {
return {
getQuestion: () => workspace.currentQuestion.value,
getCurrentQuestionIndex: () => workspace.currentQuestionIndex.value,
getAnsweredCount: () => workspace.answeredCount.value,
getTotalCount: () => workspace.totalQuestionCount.value,
getScore: () => workspace.score.value,
getSelectedOptionId: () => workspace.selectedOptionId.value,
getAnswerLocked: () => workspace.answerLocked.value,
getFeedbackCorrect: () => workspace.currentFeedbackCorrect.value,
getAnswerLabel: () => {
const q = workspace.currentQuestion.value;
if (!q) return '';
return q.options?.find((o) => o.id === workspace.selectedOptionId.value)?.label || '';
},
onSelect: workspace.selectAnswer,
onNext: workspace.moveToNextQuestion,
onPlayVideo: () => {
// 通过 DOM 事件或状态传递触发视频播放,这里我们直接让 workspace 标记视频模态框展示
// 注意:这里需要确保 TrainingWorkspacePanel 监听了对应的状态
workspace.showVideoModal.value = true;
},
onStartExam: workspace.startExam,
onRestartExam: workspace.restartExam,
getCorrectCount: () => workspace.correctCount.value,
getWrongCount: () => workspace.wrongCount.value,
getSummaryPoints: () => workspace.summaryPoints.value,
getSummaryChecklist: () => workspace.summaryChecklist.value,
};
}
/** 隐藏 file input ref 包裹,避免 template 自动解包 Ref */
export function createShippingPickerRefHolder(pickerRef: Ref<HTMLInputElement | null>) {
return { pickerRef };
@@ -0,0 +1,65 @@
/**
* features/chat/training/training.types.ts
* 用途:定义入职培训聊天工作区的题库、考试进度、HR 统计记录等共享类型。
* 依赖:被 useTrainingWorkspace 与 TrainingWorkspacePanel 共同引用。
* 逻辑:统一约束“学员考试流”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
*/
export type TrainingStage = 'video' | 'summary' | 'exam' | 'result';
export type TrainingWorkspaceView = 'learner' | 'admin';
export type TrainingQuestionType = 'single' | 'boolean';
export interface TrainingQuestionOption {
id: string;
label: string;
}
export interface TrainingQuestion {
id: string;
type: TrainingQuestionType;
prompt: string;
answer: string;
explanation: string;
options?: TrainingQuestionOption[];
}
export interface TrainingAnswerRecord {
questionId: string;
selectedOptionId: string;
correct: boolean;
}
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
export interface TrainingRecord {
id: string | number;
name: string;
employeeId: string;
department: string;
joinDate: string;
completionDate: string | null;
score: number | null;
attempts: number;
status: TrainingRecordStatus;
}
export interface TrainingProgressRecord extends TrainingRecord {
stage: TrainingStage;
currentQuestionIndex: number;
passed: boolean;
answerDetails: TrainingAnswerRecord[];
startedAt: string | null;
completionTime: string | null;
updatedAt: string | null;
}
export interface TrainingStats {
total: number;
passed: number;
failed: number;
inProgress: number;
passRate: number;
averageScore: number;
}