feat(安全培训): 新增员工安全培训相关功能

This commit is contained in:
runny committed 2026-08-12 11:56:35 +08:00
1 parent cbc3cb959f
commit 8e5c57790c
50 files changed
+3769 -87

No files matched your search

+109 -5
View File
@@ -6,11 +6,26 @@
*/
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
import type {
SafetyProgressState,
TrainingAnswerRecord,
TrainingExamMode,
TrainingProgressRecord,
TrainingPublishedConfig,
TrainingRecord,
TrainingStage,
TrainingStats,
TrainingType,
} from '../training/training.types';
type TrainingRecordApi = {
id: number;
user_id?: number;
training_type?: TrainingType;
training_version?: string | null;
exam_mode?: TrainingExamMode;
safety_stage?: string | null;
safety_progress?: Partial<SafetyProgressState> | null;
employee_id?: string | null;
name?: string | null;
department?: string | null;
@@ -31,6 +46,32 @@ type TrainingRecordApi = {
status?: TrainingRecord['status'];
};
type TrainingConfigApi = {
id: number;
training_type?: TrainingType;
version?: string | null;
pass_score?: number | null;
settings?: Record<string, unknown> | null;
resources?: Array<{
id?: number | null;
resource_type?: string | null;
training_level?: 'company' | 'department' | 'team' | null;
agent_guide_id?: number | null;
inline_questions?: unknown[];
title?: string | null;
sort_order?: number;
required_duration?: number;
resource?: {
id?: number;
file_name?: string;
file_type?: string;
file_url?: string;
guide_usage?: string;
source_file_name?: string;
} | null;
}>;
};
type TrainingListApi = {
items: TrainingRecordApi[];
total: number;
@@ -52,13 +93,19 @@ type TrainingStatsApi = {
export interface TrainingRecordQuery {
keyword?: string;
department?: string;
status?: 'all' | 'passed' | 'failed' | 'in_progress';
status?: string;
type?: string;
page?: number;
page_size?: number;
}
export interface SaveTrainingProgressPayload {
stage: TrainingStage;
agentId?: number | null;
trainingVersion?: string | null;
examMode?: TrainingExamMode;
safetyStage?: string | null;
safetyProgress?: Partial<SafetyProgressState> | null;
currentQuestionIndex: number;
score: number;
passed: boolean;
@@ -80,9 +127,20 @@ function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): Training
: [];
}
function mapSafetyProgressState(items?: TrainingRecordApi['safety_progress']): SafetyProgressState {
return {
company: String(items?.company || 'pending'),
department: String(items?.department || 'pending'),
team: String(items?.team || 'pending'),
resource_progress: (items as any)?.resource_progress || {},
};
}
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
return {
id: data.id,
trainingType: data.training_type || 'onboarding',
trainingVersion: data.training_version || undefined,
name: String(data.name || ''),
employeeId: String(data.employee_id || ''),
department: String(data.department || ''),
@@ -92,6 +150,9 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
attempts: Number(data.attempt_count || 0),
status: data.status || 'in_progress',
stage: (data.stage || 'video') as TrainingStage,
examMode: (data.exam_mode || 'unified') as TrainingExamMode,
safetyStage: data.safety_stage ? String(data.safety_stage) as TrainingProgressRecord['safetyStage'] : null,
safetyProgress: mapSafetyProgressState(data.safety_progress),
currentQuestionIndex: Number(data.current_question_index || 0),
passed: Boolean(data.passed),
answerDetails: mapAnswerDetails(data.answer_details),
@@ -101,10 +162,41 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
};
}
function mapTrainingConfig(data: TrainingConfigApi): TrainingPublishedConfig {
return {
id: data.id,
trainingType: data.training_type || 'onboarding',
version: String(data.version || ''),
passScore: Number(data.pass_score || 0),
settings: data.settings || {},
resources: Array.isArray(data.resources)
? data.resources.map((resource) => ({
id: resource.id,
resourceType: resource.resource_type,
trainingLevel: resource.training_level,
agentGuideId: resource.agent_guide_id,
inlineQuestions: resource.inline_questions,
title: resource.title,
sortOrder: Number(resource.sort_order || 0),
requiredDuration: Number(resource.required_duration || 0),
resource: resource.resource ? {
id: resource.resource.id,
fileName: resource.resource.file_name || resource.resource.source_file_name,
fileType: resource.resource.file_type,
fileUrl: resource.resource.file_url,
guideUsage: resource.resource.guide_usage,
} : null,
}))
: [],
};
}
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
const progress = mapTrainingProgressRecord(data);
return {
id: progress.id,
trainingType: progress.trainingType,
trainingVersion: progress.trainingVersion,
name: progress.name,
employeeId: progress.employeeId,
department: progress.department,
@@ -121,26 +213,38 @@ function buildQueryString(query: TrainingRecordQuery = {}) {
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.type) params.set('type', query.type);
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());
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${type}`, authHeaders());
return data ? mapTrainingProgressRecord(data) : null;
}
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
export async function getMyTrainingConfig(type: string = 'onboarding'): Promise<TrainingPublishedConfig | null> {
const data = await requestJson<TrainingConfigApi | null>(`/api/user/training-config?type=${encodeURIComponent(type)}`, authHeaders());
return data ? mapTrainingConfig(data) : null;
}
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload, type: string = 'onboarding'): Promise<TrainingProgressRecord> {
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
method: 'PUT',
...jsonAuthHeaders(),
body: JSON.stringify({
agent_id: payload.agentId || undefined,
stage: payload.stage,
training_version: payload.trainingVersion || undefined,
exam_mode: payload.examMode || undefined,
safety_stage: payload.safetyStage || undefined,
safety_progress: payload.safetyProgress || undefined,
current_question_index: payload.currentQuestionIndex,
score: payload.score,
passed: payload.passed,
attempt_count: payload.attemptCount,
type: type,
answer_details: payload.answerDetails.map((item) => ({
question_id: item.questionId,
selected_option_id: item.selectedOptionId,
@@ -20,11 +20,19 @@ import {
RefreshCcw,
ShieldCheck,
Target,
User,
FileText,
Video,
Lock,
XCircle,
} from 'lucide-vue-next';
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
import { useMessage } from '@/shared/composables/useMessage';
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
import { getAuthHeaders } from '@/shared/utils/auth';
const props = defineProps<{
currentAgent: Record<string, unknown> | null;
currentUser: Record<string, unknown> | null;
@@ -39,9 +47,13 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
const msg = useMessage();
const workspace = reactive(props.training);
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
const showFilePreview = ref(false);
// 将 workspace 内部控制弹窗的状态同步给组件本地变量(如果需要,或者直接用 workspace.showVideoModal)
const showVideoModal = computed({
get: () => workspace.showVideoModal,
@@ -82,14 +94,14 @@ const handleVideoSeeking = (e: Event) => {
};
const handleVideoEnded = () => {
showVideoModal.value = false;
workspace.markVideoCompleted();
workspace.showVideoModal = false;
workspace.stopMaterialTimer();
};
const reportVideoDebugEvent = (event: Event) => {
const video = event.target as HTMLVideoElement;
// #region debug-point A-E:ios-video-runtime
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || currentPreviewVideoUrl.value || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
// #endregion
};
@@ -227,6 +239,50 @@ const examQuestionItems = computed(() => Array.from({ length: workspace.totalQue
};
}));
const canNavigateExamQuestions = computed(() => workspace.stage === 'exam');
const isMaterialCompleted = (material: any) => {
const resourceProgress = workspace.safetyProgress.resource_progress || {};
const record = resourceProgress[material.id];
return record ? !!record.completed : false;
};
const currentPreviewVideoUrl = ref('');
const handleMaterialClick = (material: any) => {
const url = material.resource?.fileUrl;
if (!url) {
msg.warning('该资料暂无可预览的文件');
return;
}
if (material.resource?.fileType === 'video') {
workspace.showVideoModal = true;
currentPreviewVideoUrl.value = url;
// 当点击视频资料时,我们应该记录正在观看的资源ID,以便后续更新进度
workspace.currentViewingMaterialId = material.id;
} else {
previewFile.value = {
name: material.title || material.resource?.fileName || '资料预览',
url: url,
actualExt: material.resource?.fileType,
};
showFilePreview.value = true;
workspace.currentViewingMaterialId = material.id;
}
workspace.startMaterialTimer(material.id);
};
const handlePreviewClose = (val: boolean) => {
showFilePreview.value = val;
if (!val) {
workspace.stopMaterialTimer();
}
};
const handleVideoModalClose = () => {
workspace.showVideoModal = false;
currentPreviewVideoUrl.value = '';
workspace.stopMaterialTimer();
};
const jumpToExamQuestion = (index: number) => {
if (!canNavigateExamQuestions.value) return;
workspace.syncExamQuestionIndex(index);
@@ -239,6 +295,21 @@ const handleStageCardClick = (stageKey: string) => {
if (!canSwitchToStage(stageKey)) return;
workspace.stage = stageKey as typeof workspace.stage;
};
// --- 安全培训相关计算属性 ---
const safetySteps = computed(() => workspace.safetyStepItems);
const currentSafetySummary = computed(() => {
return workspace.publishedSafetySummary;
});
const currentSafetyStageText = computed(() => {
if (workspace.safetyViewStage === 'company') return t('chat.training.safety.steps.company');
if (workspace.safetyViewStage === 'department') return t('chat.training.safety.steps.department');
if (workspace.safetyViewStage === 'team') return t('chat.training.safety.steps.team');
if (workspace.safetyViewStage === 'exam') return t('chat.training.safety.steps.exam');
return t('chat.training.steps.result');
});
</script>
<template>
@@ -412,7 +483,38 @@ const handleStageCardClick = (stageKey: string) => {
</div>
<div v-if="!isCompactMode && workspace.activeView === 'learner'" :class="learnerWorkspaceGridClass">
<div :class="learnerWorkspaceMainClass">
<!-- 增加顶部 Tab 切换:入职培训 / 安全培训 -->
<div class="col-span-full mb-1">
<div class="inline-flex rounded-xl border border-default bg-surface-soft p-1">
<button
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'onboarding' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'onboarding'"
>
<User class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.onboarding') }}
</button>
<button
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'safety' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'safety'"
>
<ShieldCheck class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.safety') }}
</button>
</div>
</div>
<div v-if="workspace.trainingConfigLoading" class="col-span-full rounded-2xl border border-default bg-white px-6 py-16 text-center text-secondary">
{{ $t('chat.training.noContent.loading') }}
</div>
<div v-else-if="!workspace.hasPublishedTrainingConfig" class="col-span-full rounded-2xl border border-dashed border-brand-200 bg-white px-6 py-16 text-center text-secondary">
<FileText class="mx-auto h-10 w-10 text-brand-300" />
<div class="mt-3 text-base font-semibold text-primary">{{ $t('chat.training.noContent.title') }}</div>
<div class="mt-1 text-sm">{{ $t('chat.training.noContent.description') }}</div>
</div>
<template v-else-if="workspace.learnerTab === 'onboarding'">
<div :class="learnerWorkspaceMainClass">
<div :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
<div>
@@ -666,8 +768,39 @@ const handleStageCardClick = (stageKey: string) => {
</div>
</div>
<div class="min-w-0 md:sticky md:top-3 md:self-start">
<div :class="questionNavPanelClass">
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
<!-- 流程进度面板 (仅在非考试阶段展示) -->
<div v-if="workspace.stage !== 'exam' && workspace.stage !== 'result'" :class="questionNavPanelClass">
<div class="flex items-center gap-2 mb-3">
<Target class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.progressLabel') }}</div>
</div>
<div class="space-y-2">
<div
v-for="(item, index) in stageItems"
:key="item.key"
class="flex items-center gap-3 p-2 rounded-lg border transition"
:class="[
stageStep > index + 1 ? 'border-emerald-200 bg-emerald-50/50' :
stageStep === index + 1 ? 'border-brand-300 bg-brand-50' :
'border-slate-100 bg-slate-50/50 opacity-70'
]"
>
<div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="stageStep > index + 1 ? 'bg-emerald-500 text-white' : stageStep === index + 1 ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
>
<CheckCircle2 v-if="stageStep > index + 1" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
</div>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold" :class="stageStep === index + 1 ? 'text-brand-700' : 'text-slate-700'">{{ $t(item.label) }}</div>
</div>
</div>
</div>
</div>
<!-- 考试题目面板 (在考试或结果阶段展示) -->
<div v-else :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
@@ -709,6 +842,335 @@ const handleStageCardClick = (stageKey: string) => {
</ul>
</div>
</div>
</template>
<!-- 安全培训视图 -->
<template v-else>
<div :class="learnerWorkspaceMainClass">
<!-- 进度卡片 -->
<div :class="progressCardClass">
<div class="flex flex-col gap-1.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.safety.progressTitle') }}
</div>
<div class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
{{ $t('chat.training.safety.progressHint') }}
</div>
</div>
<div class="rounded-lg bg-surface-soft px-2.5 py-1 text-center">
<div class="text-xs text-muted">{{ $t('chat.training.progressPercent') }}</div>
<div class="text-base font-semibold leading-none text-primary">{{ workspace.safetyProgressPercent }}%</div>
</div>
</div>
<div class="mt-2 grid grid-cols-2 gap-1 lg:grid-cols-4">
<div
v-for="step in safetySteps"
:key="step.id"
class="cursor-pointer rounded-xl border px-2 py-1.5 transition"
:class="[
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50' :
step.status === 'active' ? 'border-brand-500 bg-brand-500 text-white shadow-sm' :
'border-default bg-surface-soft/70 opacity-60'
]"
@click="step.status !== 'locked' ? workspace.setSafetyStage(step.id as any) : null"
>
<div class="flex items-center gap-2">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-white text-brand-600' : 'bg-white text-muted'"
>
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
<PlayCircle v-else-if="step.id !== 'exam'" class="h-4 w-4" />
<Lock v-else-if="step.status === 'locked'" class="h-3 w-3" />
<ClipboardCheck v-else class="h-4 w-4" />
</div>
<div class="min-w-0">
<div class="whitespace-normal text-[12px] font-medium leading-4" :class="step.status === 'active' ? 'text-white' : 'text-primary'">{{ step.label }}</div>
<div class="text-[10px] font-medium mt-0.5" :class="step.status === 'active' ? 'text-white/80' : 'text-secondary'">
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 主内容区 -->
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div class="flex justify-between items-center">
<div>
<span class="inline-flex rounded-md bg-amber-500 px-2 py-0.5 text-xs font-semibold text-white">
{{ currentSafetyStageText }}
</span>
<span class="ml-2 text-base font-semibold text-primary">{{ $t('chat.training.safety.videoPanelSubtitle') }}</span>
</div>
<div class="text-xs font-medium text-amber-500">
{{ $t('chat.training.safety.videoPanelPassLine') }}
</div>
</div>
<div class="mt-4">
<div class="text-sm font-semibold text-primary mb-3">{{ $t('chat.training.safety.materialsTitle') }}</div>
<ul v-if="workspace.publishedTrainingMaterials.length" class="space-y-2">
<li v-for="material in workspace.publishedTrainingMaterials" :key="material.id || `${material.resourceType}-${material.sortOrder}`" class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 cursor-pointer hover:bg-slate-100 transition" @click="handleMaterialClick(material)">
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary hover:text-brand-600">
<Video v-if="material.resource?.fileType === 'video'" class="h-4 w-4 text-brand-500" />
<FileText v-else class="h-4 w-4 text-slate-400" />
<span class="truncate">{{ material.title || material.resource?.fileName || $t('chat.training.safety.materials.m2') }}</span>
</div>
<div class="flex flex-col items-end gap-1">
<span class="text-xs text-secondary">{{ currentSafetyStageText }}</span>
<span v-if="material.requiredDuration" class="text-xs font-semibold" :class="isMaterialCompleted(material) ? 'text-emerald-500' : 'text-amber-500'">所需时间: {{ material.requiredDuration }} 分钟 ({{ isMaterialCompleted(material) ? '已完成' : '未完成' }})</span>
</div>
</li>
</ul>
</div>
</div>
<div v-else-if="workspace.safetyViewStage === 'exam' && workspace.currentQuestion" :class="examPanelClass">
<div class="flex flex-col gap-2.5 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.safety.steps.exam') }}
</div>
<h3 class="mt-1 text-base font-semibold text-primary md:text-lg">
{{ $t('chat.training.exam.questionCounter', { current: workspace.currentQuestionNumber, total: workspace.totalQuestionCount }) }}
</h3>
</div>
<div class="flex flex-wrap gap-1.5 text-xs text-secondary md:text-sm">
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
</div>
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
</div>
</div>
</div>
<div class="mt-3 rounded-2xl border border-brand-100 bg-brand-50/40 p-3">
<div class="text-[15px] font-semibold leading-6 text-primary md:text-base">
{{ workspace.currentQuestion.prompt }}
</div>
</div>
<div class="mt-2.5 grid gap-2">
<button
v-for="option in workspace.currentQuestion.options"
:key="option.id"
type="button"
class="rounded-2xl border px-3.5 py-2 text-left text-sm leading-5 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',
]"
@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-3 rounded-2xl border p-3"
: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 text-sm font-medium text-white transition hover:bg-brand-700"
@click="workspace.examReadyToSubmit ? workspace.submitExam() : workspace.moveToNextQuestion()"
>
<ClipboardCheck class="h-4 w-4" />
{{
workspace.examReadyToSubmit
? $t('chat.training.exam.submitPaper')
: $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', { passScore: workspace.passScore }) }}
</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>
</div>
</div>
</div>
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
<!-- 流程进度面板 (仅在非考试阶段展示) -->
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'" :class="questionNavPanelClass">
<div class="flex items-center gap-2 mb-3">
<Target class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.safety.progressTitle') }}</div>
</div>
<div class="space-y-2">
<div
v-for="(step, index) in safetySteps"
:key="step.id"
class="flex items-center gap-3 p-2 rounded-lg border transition"
:class="[
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50/50' :
step.status === 'active' ? 'border-brand-300 bg-brand-50' :
'border-slate-100 bg-slate-50/50 opacity-70'
]"
>
<div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
>
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
</div>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold" :class="step.status === 'active' ? 'text-brand-700' : 'text-slate-700'">{{ step.label }}</div>
<div class="text-[10px] text-slate-500 mt-0.5">
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 考试题目面板 (在考试阶段或结果阶段展示) -->
<div v-else :class="questionNavPanelClass">
<div class="flex items-center gap-2">
<ClipboardCheck class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
</div>
<div class="mt-1.5 text-[11px] leading-4.5 text-secondary">
{{ $t('chat.training.examQuestionCard.hint') }}
</div>
<div :class="questionNavGridClass">
<button
v-for="item in examQuestionItems"
:key="item.index"
type="button"
:class="[
questionNavButtonClass,
item.status === 'active'
? 'border-brand-500 bg-brand-600 text-white shadow-sm'
: item.status === 'correct'
? 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
: item.status === 'wrong'
? 'border-red-200 bg-red-50 text-red-700 hover:bg-red-100'
: 'border-default bg-surface-soft text-muted hover:border-slate-300 hover:bg-slate-100',
!canNavigateExamQuestions ? 'cursor-not-allowed opacity-80' : '',
]"
:disabled="!canNavigateExamQuestions"
@click="jumpToExamQuestion(item.index)"
>
{{ item.label }}
</button>
</div>
<div class="my-2.5 h-px bg-slate-100" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
<ul class="mt-1.5 grid gap-1 text-[11px] leading-4.5 text-secondary">
<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>{{ rule }}</span>
</li>
</ul>
</div>
<!-- 培训总结 -->
<div v-if="currentSafetySummary && currentSafetySummary.length > 0" :class="questionNavPanelClass" class="bg-amber-50/50 border-amber-100">
<div class="text-sm font-semibold text-amber-900 mb-2">{{ $t('chat.training.safety.summaryTitle') }}</div>
<ul class="space-y-1.5 text-[11px] leading-4.5 text-amber-800/80">
<li v-for="(point, idx) in currentSafetySummary" :key="idx" class="flex gap-1.5">
<span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-amber-400"></span>
<span>{{ point }}</span>
</li>
</ul>
</div>
</div>
</template>
</div>
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
@@ -747,7 +1209,7 @@ const handleStageCardClick = (stageKey: string) => {
<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-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
<label>
<input
v-model="workspace.hrKeyword"
@@ -756,6 +1218,16 @@ const handleStageCardClick = (stageKey: string) => {
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
/>
</label>
<label>
<select
v-model="workspace.hrTypeFilter"
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.allTypes') }}</option>
<option value="onboarding">{{ $t('chat.training.hr.filters.typeOnboarding') }}</option>
<option value="safety">{{ $t('chat.training.hr.filters.typeSafety') }}</option>
</select>
</label>
<label>
<select
v-model="workspace.hrStatusFilter"
@@ -840,9 +1312,9 @@ const handleStageCardClick = (stageKey: string) => {
</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 v-if="workspace.showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="handleVideoModalClose">
<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">
<button @click="handleVideoModalClose" 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">
@@ -863,11 +1335,18 @@ const handleStageCardClick = (stageKey: string) => {
@seeking="handleVideoSeeking"
@ended="handleVideoEnded"
>
<source :src="workspace.videoUrl" type="video/mp4">
<source :src="currentPreviewVideoUrl || workspace.videoUrl" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
</div>
<FilePreviewModal
v-model="showFilePreview"
:file="previewFile"
:agent-id="workspace.currentTrainingAgentId || undefined"
:auth-headers="getAuthHeaders()"
@update:modelValue="handlePreviewClose"
/>
</Teleport>
</template>
@@ -10,33 +10,40 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
exportTrainingRecords,
getMyTrainingConfig,
getMyTrainingProgress,
getTrainingStats,
listTrainingRecords,
saveMyTrainingProgress,
} from '@/features/chat/api/training.api';
import type {
SafetyProgressState,
TrainingAnswerRecord,
TrainingContentConfig,
TrainingExamMode,
TrainingExamTransitionFeedback,
TrainingQuestion,
TrainingQuestionOption,
TrainingProgressRecord,
TrainingPublishedConfig,
TrainingRecord,
TrainingRecordStatus,
SafetyStage,
TrainingStage,
TrainingStats,
TrainingType,
TrainingWorkspaceView,
} from '@/features/chat/training/training.types';
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
matchesTrainingAgent,
resolveTrainingContentConfig,
resolveTrainingVideoGuide,
resolveTrainingVideoUrl,
resolveSafetyTrainingVideoGuide,
type TrainingGuideLike,
} from '@/features/chat/training/trainingWorkspace.utils';
type TrainingAgentLike = {
id?: number | null;
name?: string | null;
extra_config?: Record<string, unknown> | null;
} | null | undefined;
@@ -52,14 +59,19 @@ type TrainingUserLike = {
} | null;
} | null | undefined;
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
currentGuides: ComputedRef<TrainingGuideLike[]>;
}
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION: Record<TrainingType, string> = {
onboarding: 'onboarding-v1',
safety: 'safety-v1',
};
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -78,10 +90,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const msg = useMessage();
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
const currentTrainingAgentId = computed<number | null>(() => {
const parsed = Number(currentAgent.value?.id);
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
});
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
const activeView = ref<TrainingWorkspaceView>('learner');
const learnerTab = ref<TrainingType>('onboarding');
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION.onboarding);
const examMode = ref<TrainingExamMode>('unified');
const safetyStage = ref<SafetyStage>('company');
const safetyViewStage = ref<SafetyStage>('company');
const safetyProgress = ref<SafetyProgressState>({
company: 'active',
department: 'pending',
team: 'pending',
});
const stage = ref<TrainingStage>('video');
const currentQuestionIndex = ref(0);
@@ -103,10 +129,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const isHydrated = ref(false);
const hasWarnedPersistFailure = ref(false);
const hasWarnedLoadFailure = ref(false);
const publishedConfig = ref<TrainingPublishedConfig | null>(null);
const trainingConfigLoading = ref(false);
const hrKeyword = ref('');
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
const hrDepartmentFilter = ref('all');
const hrTypeFilter = ref('all');
const records = ref<TrainingRecord[]>([]);
const departmentOptions = ref<string[]>([]);
const stats = ref<TrainingStats>({
@@ -190,12 +219,42 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
questionBank: defaultQuestionBank.value,
},
booleanOptions.value,
publishedConfig.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 hasPublishedTrainingConfig = computed(() => publishedConfig.value !== null);
const activeSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyStage.value)
? safetyStage.value as SafetyLearningStage
: null
));
const visibleSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
['company', 'department', 'team'].includes(safetyViewStage.value)
? safetyViewStage.value as SafetyLearningStage
: null
));
const resolveSafetyStageMaterials = (targetStage: SafetyLearningStage | null) => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => !targetStage || resource.trainingLevel === targetStage)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0));
/**
* 按当前安全培训阶段筛选已发布资料。
* AI 触发时机:员工进入公司级、部门级或班组级页面时,只展示后台绑定到当前级别的资料;入职培训仍展示全部非题库资料。
*/
const publishedTrainingMaterials = computed(() => [...(publishedConfig.value?.resources || [])]
.filter((resource) => resource.resourceType !== 'inline_questions')
.filter((resource) => learnerTab.value !== 'safety' || resource.trainingLevel === visibleSafetyLearningStage.value)
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0)));
const publishedSafetySummary = computed(() => {
const summaries = publishedConfig.value?.settings?.summaryByStage;
if (!summaries || typeof summaries !== 'object') return [];
const value = (summaries as Record<string, unknown>)[safetyViewStage.value];
return Array.isArray(value) ? value.map((item) => String(item)) : [];
});
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
const totalQuestionCount = computed(() => questionBank.value.length);
@@ -213,8 +272,55 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
&& answeredCount.value >= totalQuestionCount.value
));
const canEnterResultStage = computed(() => stage.value === 'result');
const safetyProgressPercent = computed(() => {
if (safetyStage.value === 'company') return 25;
if (safetyStage.value === 'department') return 50;
if (safetyStage.value === 'team') return 75;
if (safetyStage.value === 'exam') return 90;
return 100;
});
const safetyStepItems = computed(() => {
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
{ id: 'department', labelKey: 'chat.training.safety.steps.department' },
{ id: 'team', labelKey: 'chat.training.safety.steps.team' },
{ id: 'exam', labelKey: 'chat.training.safety.steps.exam' },
];
return base.map((item) => {
let status: 'completed' | 'active' | 'pending' | 'locked' = 'pending';
if (item.id === 'company') {
status = safetyProgress.value.company === 'completed'
? 'completed'
: safetyProgress.value.company === 'active' ? 'active' : 'pending';
} else if (item.id === 'department') {
status = safetyProgress.value.department === 'completed'
? 'completed'
: safetyProgress.value.department === 'active' ? 'active' : 'pending';
} else if (item.id === 'team') {
status = safetyProgress.value.team === 'completed'
? 'completed'
: safetyProgress.value.team === 'active' ? 'active' : 'pending';
} else if (item.id === 'exam') {
status = ['exam', 'result'].includes(safetyStage.value)
? (safetyStage.value === 'exam' ? 'active' : 'completed')
: (safetyProgress.value.company === 'completed'
&& safetyProgress.value.department === 'completed'
&& safetyProgress.value.team === 'completed'
? 'pending'
: 'locked');
}
return {
id: item.id,
label: t(item.labelKey),
status,
};
});
});
const learnerProgressPercent = computed(() => {
if (learnerTab.value === 'safety') {
return safetyProgressPercent.value;
}
if (stage.value === 'video') return 25;
if (stage.value === 'summary') return 50;
if (stage.value === 'result') return 100;
@@ -353,14 +459,69 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 按安全培训目标阶段重置三级学习进度。
* AI 触发时机:当员工完成上一级学习、切换安全培训阶段,或后端恢复安全培训初始态时,需要一次性得到完整的三级状态快照。
*/
const resetSafetyProgress = (nextStage: SafetyStage = 'company') => {
const resourceProgressSnapshot = safetyProgress.value.resource_progress
? { ...safetyProgress.value.resource_progress }
: undefined;
safetyStage.value = nextStage;
safetyViewStage.value = nextStage;
if (nextStage === 'company') {
safetyProgress.value = { company: 'active', department: 'pending', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'department') {
safetyProgress.value = { company: 'completed', department: 'active', team: 'pending', resource_progress: resourceProgressSnapshot };
return;
}
if (nextStage === 'team') {
safetyProgress.value = { company: 'completed', department: 'completed', team: 'active', resource_progress: resourceProgressSnapshot };
return;
}
safetyProgress.value = { company: 'completed', department: 'completed', team: 'completed', resource_progress: resourceProgressSnapshot };
};
/**
* 进入安全培训考试阶段并初始化本轮考试状态。
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
*/
const enterSafetyExam = () => {
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
}
safetyStage.value = 'exam';
safetyViewStage.value = 'exam';
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
};
/**
* 把后端培训记录回填到当前工作区状态。
* AI 触发时机:页面刷新、重新进入聊天页或切换培训类型后,需要把服务端快照完整恢复到本地状态机。
*/
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
if (!record) {
trainingVersion.value = DEFAULT_TRAINING_VERSION[learnerTab.value];
examMode.value = 'unified';
resetSafetyProgress('company');
stage.value = 'video';
resetExamState();
currentJoinDate.value = null;
latestSettledResult.value = null;
return;
}
trainingVersion.value = record.trainingVersion || DEFAULT_TRAINING_VERSION[learnerTab.value];
examMode.value = record.examMode || 'unified';
if (learnerTab.value === 'safety') {
safetyStage.value = record.safetyStage || 'company';
safetyProgress.value = record.safetyProgress;
safetyViewStage.value = record.safetyStage || 'company';
}
stage.value = record.stage;
syncExamQuestionIndex(record.currentQuestionIndex);
score.value = Number(record.score || 0);
@@ -387,8 +548,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
syncAnswerStateForCurrentQuestion();
};
/**
* 组装当前培训工作区的持久化载荷。
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
*/
const buildProgressPayload = () => ({
stage: stage.value,
agentId: currentTrainingAgentId.value,
stage: learnerTab.value === 'safety'
? (safetyStage.value === 'exam' ? 'exam' : safetyStage.value === 'result' ? 'result' : 'summary')
: stage.value,
trainingVersion: trainingVersion.value,
examMode: examMode.value,
safetyStage: learnerTab.value === 'safety' ? safetyStage.value : null,
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
currentQuestionIndex: currentQuestionIndex.value,
score: score.value,
passed: isPassed.value,
@@ -401,7 +573,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
if (!isTrainingAgent.value) return;
persistQueue = persistQueue.catch(() => undefined).then(async () => {
try {
const saved = await saveMyTrainingProgress(buildProgressPayload());
const saved = await saveMyTrainingProgress(buildProgressPayload(), learnerTab.value);
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
@@ -433,7 +605,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
try {
const record = await getMyTrainingProgress();
const record = await getMyTrainingProgress(learnerTab.value);
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
@@ -459,6 +631,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
}
};
const loadTrainingConfig = async () => {
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) {
publishedConfig.value = null;
trainingConfigLoading.value = false;
return;
}
trainingConfigLoading.value = true;
try {
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
} catch (error) {
if (!(error instanceof BusinessError && error.status === 401)) {
publishedConfig.value = null;
}
} finally {
trainingConfigLoading.value = false;
}
};
const loadAdminRecords = async () => {
if (!isTrainingAgent.value || !isAdminViewer.value) return;
try {
@@ -466,6 +656,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
};
const [recordData, statsData] = await Promise.all([
listTrainingRecords(query),
@@ -494,6 +685,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hasAuthenticatedUser,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
learnerTab,
],
([agent, loggedIn]) => {
if (!matchesTrainingAgent(agent)) {
@@ -516,6 +708,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
isHydrated.value = false;
void loadTrainingConfig();
void loadTrainingProgress();
},
{ immediate: true },
@@ -528,6 +721,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrTypeFilter,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
@@ -539,11 +733,30 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (learnerTab.value === 'safety') {
if (safetyStage.value === 'company') {
resetSafetyProgress('department');
} else if (safetyStage.value === 'department') {
resetSafetyProgress('team');
} else if (safetyStage.value === 'team') {
resetSafetyProgress('exam');
enterSafetyExam();
}
void persistProgress();
return;
}
stage.value = 'summary';
void persistProgress();
};
const startExam = () => {
if (!hasPublishedTrainingConfig.value) return;
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
if (totalQuestionCount.value <= 0) {
msg.warning(t('chat.training.errors.questionBankEmpty'));
return;
@@ -614,6 +827,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const submitExam = () => {
if (!examReadyToSubmit.value) return;
stage.value = 'result';
if (learnerTab.value === 'safety') {
safetyStage.value = 'result';
safetyViewStage.value = 'result';
}
completionDate.value = formatDate(new Date());
latestSettledResult.value = {
score: score.value,
@@ -625,16 +842,34 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
};
const restartExam = () => {
if (learnerTab.value === 'safety') {
enterSafetyExam();
void persistProgress();
return;
}
stage.value = 'video';
resetExamState();
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
};
/**
* 按右侧步骤面板切换安全培训阶段。
* AI 触发时机:当员工点击安全培训流程步骤时,只允许查看当前可达阶段,
* 但绝不能因为“返回查看已完成阶段”而重置已保存的完成状态或学习记录。
*/
const setSafetyStage = (nextStage: SafetyStage) => {
if (!hasPublishedTrainingConfig.value) return;
const target = safetyStepItems.value.find((item) => item.id === nextStage);
if (!target || target.status === 'locked') return;
safetyViewStage.value = nextStage;
};
const exportRecords = async () => {
await exportTrainingRecords({
keyword: hrKeyword.value || undefined,
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
status: hrStatusFilter.value,
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
});
};
@@ -642,6 +877,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
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.typeLabel')}: ${hrTypeFilter.value === 'all' ? t('chat.training.hr.filters.allTypes') : hrTypeFilter.value === 'safety' ? t('chat.training.hr.filters.typeSafety') : t('chat.training.hr.filters.typeOnboarding')}`,
`${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}%`,
@@ -691,17 +927,109 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
});
const showVideoModal = ref(false);
const currentViewingMaterialId = ref<number | null>(null);
const materialStartTime = ref<number>(0);
const startMaterialTimer = (materialId: number) => {
currentViewingMaterialId.value = materialId;
materialStartTime.value = Date.now();
};
const stopMaterialTimer = () => {
if (!currentViewingMaterialId.value || !materialStartTime.value) return;
const materialId = String(currentViewingMaterialId.value);
// 累计观看时长(秒)
const durationSeconds = Math.round((Date.now() - materialStartTime.value) / 1000);
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === materialId);
if (resource) {
if (!safetyProgress.value.resource_progress) {
safetyProgress.value.resource_progress = {};
}
const existing = safetyProgress.value.resource_progress[materialId] || { duration: 0, completed: false };
existing.duration += durationSeconds;
const reqDurationMinutes = resource.requiredDuration || 0;
if (existing.duration >= reqDurationMinutes * 60) {
existing.completed = true;
}
safetyProgress.value.resource_progress[materialId] = existing;
checkAndAdvanceStage();
}
currentViewingMaterialId.value = null;
materialStartTime.value = 0;
};
const checkAndAdvanceStage = () => {
const activeStageMaterials = learnerTab.value === 'safety'
? resolveSafetyStageMaterials(activeSafetyLearningStage.value)
: publishedTrainingMaterials.value;
if (!activeStageMaterials.length) return;
const allCompleted = activeStageMaterials.every(m => {
if (m.id == null) return true;
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
return progress?.completed;
});
if (allCompleted) {
if (learnerTab.value === 'safety') {
if (safetyStage.value === 'company') {
resetSafetyProgress('department');
} else if (safetyStage.value === 'department') {
resetSafetyProgress('team');
} else if (safetyStage.value === 'team') {
resetSafetyProgress('exam');
enterSafetyExam();
}
} else {
stage.value = 'summary';
}
void persistProgress();
} else {
void persistProgress();
}
};
const videoUrl = computed(() => {
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
if (!publishedConfig.value) return '';
const visibleGuideStage = visibleSafetyLearningStage.value || activeSafetyLearningStage.value;
const preferredGuideIds = publishedTrainingMaterials.value
.filter((resource) => resource.resourceType === 'agent_guide' && resource.agentGuideId != null)
.map((resource) => Number(resource.agentGuideId));
const uploadedGuide = learnerTab.value === 'safety'
? resolveSafetyTrainingVideoGuide(currentGuides.value, visibleGuideStage || 'company', preferredGuideIds)
: currentGuides.value.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video');
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
const configuredGuide = publishedTrainingMaterials.value
.find((resource) => resource.resourceType === 'agent_guide'
&& resource.resource?.fileType === 'video'
&& (learnerTab.value !== 'safety'
|| !visibleGuideStage
|| !SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|| resource.resource.guideUsage === SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]));
return String(configuredGuide?.resource?.fileUrl || '').trim()
|| uploadedGuideUrl;
});
return {
isTrainingAgent,
isAdminViewer,
isHydrated,
trainingConfigLoading,
hasPublishedTrainingConfig,
publishedTrainingMaterials,
publishedSafetySummary,
activeView,
learnerTab,
trainingVersion,
examMode,
safetyStage,
safetyViewStage,
safetyProgress,
safetyProgressPercent,
safetyStepItems,
stage,
currentQuestionIndex,
currentQuestionNumber,
@@ -731,8 +1059,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
currentUserEmployeeId,
currentUserDepartment,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrStatusFilter,
hrTypeFilter,
departmentOptions,
filteredRecords,
stats,
@@ -748,8 +1077,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
moveToNextQuestion,
submitExam,
restartExam,
setSafetyStage,
exportRecords,
showVideoModal,
videoUrl,
startMaterialTimer,
stopMaterialTimer,
currentViewingMaterialId,
currentTrainingAgentId,
};
}
@@ -1,12 +1,18 @@
/**
* features/chat/training/training.types.ts
* 用途:定义入职培训聊天工作区的题库、考试进度、HR 统计记录等共享类型。
* 依赖:被 useTrainingWorkspace 与 TrainingWorkspacePanel 共同引用。
* 逻辑:统一约束“学员考试流”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
* 用途:定义员工培训工作区的共享类型,覆盖入职培训、安全培训、考试过程和 HR 统计记录。
* 依赖:被 useTrainingWorkspace、training.api 与 TrainingWorkspacePanel 共同引用。
* 逻辑:统一约束“多培训类型学员流程”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
*/
export type TrainingType = 'onboarding' | 'safety';
export type TrainingStage = 'video' | 'summary' | 'exam' | 'result';
export type TrainingExamMode = 'unified' | 'per_level';
export type SafetyStage = 'company' | 'department' | 'team' | 'exam' | 'result';
export type TrainingWorkspaceView = 'learner' | 'admin';
export type TrainingQuestionType = 'single' | 'boolean';
@@ -32,6 +38,33 @@ export interface TrainingContentConfig {
questionBank: TrainingQuestion[];
}
export interface TrainingPublishedConfigResource {
id?: number | null;
resourceType?: string | null;
trainingLevel?: Exclude<SafetyStage, 'exam' | 'result'> | null;
agentGuideId?: number | null;
inlineQuestions?: unknown[];
title?: string | null;
sortOrder?: number;
requiredDuration?: number;
resource?: {
id?: number;
fileName?: string;
fileType?: string;
fileUrl?: string;
guideUsage?: string;
} | null;
}
export interface TrainingPublishedConfig {
id: number;
trainingType: TrainingType;
version: string;
passScore: number;
settings: Record<string, unknown>;
resources: TrainingPublishedConfigResource[];
}
export interface TrainingAnswerRecord {
questionId: string;
selectedOptionId: string;
@@ -50,8 +83,17 @@ export interface TrainingExamTransitionFeedback {
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
export interface SafetyProgressState {
company: string;
department: string;
team: string;
resource_progress?: Record<string, { duration: number; completed: boolean }>;
}
export interface TrainingRecord {
id: string | number;
trainingType?: TrainingType;
trainingVersion?: string;
name: string;
employeeId: string;
department: string;
@@ -64,6 +106,9 @@ export interface TrainingRecord {
export interface TrainingProgressRecord extends TrainingRecord {
stage: TrainingStage;
examMode: TrainingExamMode;
safetyStage: SafetyStage | null;
safetyProgress: SafetyProgressState;
currentQuestionIndex: number;
passed: boolean;
answerDetails: TrainingAnswerRecord[];
@@ -4,7 +4,7 @@
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
*/
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
import type { TrainingContentConfig, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
type TrainingAgentLike = {
name?: string | null;
@@ -24,6 +24,11 @@ export type TrainingGuideLike = {
} | null | undefined;
export const TRAINING_CONTENT_PROFILE = 'training';
export const SAFETY_STAGE_GUIDE_USAGE_MAP = {
company: 'training_safety_company_video',
department: 'training_safety_department_video',
team: 'training_safety_team_video',
} as const;
/**
* 判断当前 Agent 是否应启用培训工作区。
@@ -143,6 +148,30 @@ export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | u
);
}
/**
* 按安全培训当前级别查找对应视频指南。
* AI 触发时机:当员工在安全培训中切换“公司级 / 部门级 / 班组级”阶段时,工作区必须优先展示该级别绑定的视频,而不是沿用通用安全培训视频。
*/
export function resolveSafetyTrainingVideoGuide(
guides: TrainingGuideLike[] | null | undefined,
safetyStage: keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP | 'exam' | 'result',
preferredGuideIds: number[] = [],
): TrainingGuideLike {
const normalized = Array.isArray(guides) ? guides : [];
const stageUsage = safetyStage in SAFETY_STAGE_GUIDE_USAGE_MAP
? SAFETY_STAGE_GUIDE_USAGE_MAP[safetyStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
: null;
return (
normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video' && (!stageUsage || guide?.guide_usage === stageUsage))
|| normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video')
|| (stageUsage
? normalized.find((guide) => guide?.guide_usage === stageUsage && guide?.file_type === 'video')
: null)
|| normalized.find((guide) => guide?.guide_usage === 'training_safety_video' && guide?.file_type === 'video')
|| null
);
}
/**
* 查找培训工作区优先使用的试题 PDF。
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
@@ -163,24 +192,35 @@ export function resolveTrainingContentConfig(
agent: TrainingAgentLike,
fallback: TrainingContentConfig,
booleanOptions: TrainingQuestionOption[],
publishedConfig?: TrainingPublishedConfig | null,
): TrainingContentConfig {
if (!publishedConfig) {
return { passScore: fallback.passScore, summaryPoints: [], summaryChecklist: [], questionBank: [] };
}
const extraConfig = asRecord(agent?.extra_config);
const trainingConfig = asRecord(extraConfig.training_config);
const mergedConfig = {
...extraConfig,
...trainingConfig,
...(publishedConfig.settings || {}),
};
const publishedQuestions = (publishedConfig?.resources || [])
.filter((resource) => resource.resourceType === 'inline_questions')
.flatMap((resource) => Array.isArray(resource.inlineQuestions) ? resource.inlineQuestions : []);
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
const questionBank = normalizeQuestionBank(
mergedConfig.question_bank ?? mergedConfig.questionBank,
publishedQuestions.length
? publishedQuestions
: mergedConfig.questions ?? mergedConfig.question_bank ?? mergedConfig.questionBank,
booleanOptions,
);
return {
passScore: normalizePassScore(
mergedConfig.pass_score ?? mergedConfig.passScore,
publishedConfig?.passScore ?? mergedConfig.pass_score ?? mergedConfig.passScore,
fallback.passScore || DEFAULT_PASS_SCORE,
),
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,