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

@@ -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,
};
}