Files
syops/frontend/src/features/chat/composables/useTrainingWorkspace.ts
T

1127 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 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 { 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,
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;
type TrainingUserLike = {
role?: string | null;
username?: string | null;
real_name?: string | null;
employee_id?: string | null;
department?: string | null;
feature_permissions?: {
training_hr_manage?: boolean;
} | null;
} | null | undefined;
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
export interface UseTrainingWorkspaceOptions {
currentAgent: ComputedRef<TrainingAgentLike>;
currentUser: ComputedRef<TrainingUserLike>;
currentGuides: ComputedRef<TrainingGuideLike[]>;
}
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);
/**
* 按百分制计算当前答题得分。
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
*/
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
if (totalQuestionCount <= 0) return 0;
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
};
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const { currentAgent, currentUser, currentGuides } = options;
const { t, tm } = useI18n();
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);
const score = ref(0);
const attemptCount = ref(0);
const selectedOptionId = ref('');
const answerLocked = ref(false);
const currentFeedbackCorrect = ref(false);
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
const latestSettledResult = ref<{
score: number;
correctCount: number;
wrongCount: number;
isPassed: boolean;
} | null>(null);
const answerRecords = ref<TrainingAnswerRecord[]>([]);
const completionDate = ref<string | null>(null);
const currentJoinDate = ref<string | null>(null);
const isHydrated = ref(false);
const hasWarnedPersistFailure = ref(false);
const hasWarnedLoadFailure = ref(false);
const 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>({
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;
}
});
watch(
[isTrainingAgent, isAdminViewer],
([enabled]) => {
if (!enabled) return;
activeView.value = defaultActiveView.value;
},
{ immediate: true },
);
const defaultSummaryPoints = computed(() => {
const raw = tm('chat.training.summaryPoints');
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
});
const defaultSummaryChecklist = 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 mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.map((item) => {
const type = String(item.type || 'single') as TrainingQuestion['type'];
const rawOptions = Array.isArray(item.options) ? item.options : [];
const options = type === 'boolean'
? 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 defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
currentAgent.value,
{
passScore: DEFAULT_PASS_SCORE,
summaryPoints: defaultSummaryPoints.value,
summaryChecklist: defaultSummaryChecklist.value,
questionBank: defaultQuestionBank.value,
},
booleanOptions.value,
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);
const currentQuestionNumber = computed(() => {
if (totalQuestionCount.value <= 0) return 0;
return Math.min(currentQuestionIndex.value + 1, totalQuestionCount.value);
});
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 >= passScore.value);
const examReadyToSubmit = computed(() => (
stage.value === 'exam'
&& totalQuestionCount.value > 0
&& answeredCount.value >= totalQuestionCount.value
));
const canEnterResultStage = computed(() => stage.value === 'result');
const safetyProgressPercent = computed(() => {
if (safetyStage.value === 'exam') return 90;
if (safetyStage.value === 'result') return 100;
let completedCount = 0;
if (isStageCompleted('company')) completedCount++;
if (isStageCompleted('department')) completedCount++;
if (isStageCompleted('team')) completedCount++;
return Math.round((completedCount / 3) * 75) || 10; // Start at 10% or just based on completed
});
const isStageCompleted = (stageKey: SafetyLearningStage) => {
const materials = resolveSafetyStageMaterials(stageKey);
if (!materials.length) return true;
return materials.every(m => {
if (m.id == null) return true;
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
return progress?.completed;
});
};
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' || item.id === 'department' || item.id === 'team') {
const completed = isStageCompleted(item.id);
if (safetyViewStage.value === item.id) {
status = 'active';
} else if (completed) {
status = 'completed';
} else {
status = 'pending';
}
} else if (item.id === 'exam') {
const allCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
if (['exam', 'result'].includes(safetyStage.value)) {
status = safetyStage.value === 'exam' ? 'active' : 'completed';
} else {
status = allCompleted ? '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;
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;
latestExamFeedback.value = null;
answerRecords.value = [];
completionDate.value = null;
};
/**
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
*/
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
if (!question) return optionId;
return question.options?.find((item) => item.id === optionId)?.label || optionId;
};
/**
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
*/
const buildExamFeedback = (
question: TrainingQuestion | null,
answerRecord: TrainingAnswerRecord | null | undefined,
scoreAfterAnswer: number,
): TrainingExamTransitionFeedback | null => {
if (!question || !answerRecord) return null;
return {
questionId: question.id,
questionPrompt: question.prompt,
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
explanation: question.explanation,
correct: Boolean(answerRecord.correct),
scoreAfterAnswer,
};
};
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
question?.type === 'boolean'
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
: t('chat.training.chatPrompts.assistantQuestionSingleType')
);
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
if (!question) return '';
const optionLines = (question.options || []).map((option) => option.label).join('\n');
return [
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
optionLines,
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
].filter(Boolean).join('\n');
};
const buildSummaryAssistantMessage = () => {
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
return [
t('chat.training.chatPrompts.assistantSummaryIntro'),
summaryLines,
'',
t('chat.training.chatPrompts.assistantSummaryReady'),
].join('\n');
};
/**
* 基于当前答题记录重算成绩,保证“修改答案”后分数与结果页口径一致。
* AI 触发时机:当培训考试支持点击题号返回修改答案时,不能再用“上一题答对就直接 +1”的增量算法。
*/
const recalculateScoreFromAnswers = (records: TrainingAnswerRecord[]) => calculateTrainingScore(
records.filter((item) => item.correct).length,
totalQuestionCount.value,
);
/**
* 覆盖或新增当前题的作答记录,避免同一道题在进度里出现重复答案。
* AI 触发时机:当员工返回已答题修改答案时,必须覆盖旧答案而不是重复追加,否则分数和已答题数都会失真。
*/
const upsertAnswerRecord = (nextRecord: TrainingAnswerRecord) => {
const existingIndex = answerRecords.value.findIndex((item) => item.questionId === nextRecord.questionId);
if (existingIndex >= 0) {
answerRecords.value.splice(existingIndex, 1, nextRecord);
return true;
}
answerRecords.value.push(nextRecord);
return false;
};
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);
};
/**
* 切换考试题目时,同步左侧题干、已答状态和反馈展示。
* AI 触发时机:当员工点击右侧题号导航或后端恢复考试进度时,必须保证“当前题序号、选中项、答题对错反馈”完全一致。
*/
const syncExamQuestionIndex = (nextIndex: number) => {
if (totalQuestionCount.value <= 0) {
currentQuestionIndex.value = 0;
syncAnswerStateForCurrentQuestion();
return;
}
const normalizedIndex = Math.min(Math.max(nextIndex, 0), totalQuestionCount.value - 1);
currentQuestionIndex.value = normalizedIndex;
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';
// Ensure resource_progress is preserved when merging from backend
safetyProgress.value = {
...record.safetyProgress,
resource_progress: record.safetyProgress?.resource_progress || safetyProgress.value.resource_progress || {}
};
// Sync legacy fields with actual resource completion
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
if (safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
if (!isStageCompleted('company')) {
safetyViewStage.value = 'company';
} else if (!isStageCompleted('department')) {
safetyViewStage.value = 'department';
} else if (!isStageCompleted('team')) {
safetyViewStage.value = 'team';
} else {
safetyViewStage.value = 'company';
}
} else {
safetyViewStage.value = record.safetyStage || 'company';
}
}
stage.value = record.stage;
syncExamQuestionIndex(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;
latestExamFeedback.value = null;
if (record.stage === 'result') {
latestSettledResult.value = {
score: Number(record.score || 0),
correctCount: answerRecords.value.filter((item) => item.correct).length,
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
};
}
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
const previousAnswer = previousQuestion
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
: null;
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
}
syncAnswerStateForCurrentQuestion();
};
/**
* 组装当前培训工作区的持久化载荷。
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
*/
const buildProgressPayload = () => ({
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,
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(), learnerTab.value);
hasWarnedPersistFailure.value = false;
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
completionDate.value = saved.completionDate;
if (isAdminViewer.value) {
void loadAdminRecords();
}
} catch (error) {
if (!hasWarnedPersistFailure.value) {
hasWarnedPersistFailure.value = true;
const message = error instanceof BusinessError
? error.message
: t('errors.generic');
msg.error({
title: t('chat.training.errors.persistTitle'),
message: `${t('chat.training.errors.persistBody')}:${message}`,
});
}
}
});
await persistQueue;
};
const loadTrainingProgress = async () => {
if (!isTrainingAgent.value) return;
if (!hasAuthenticatedUser.value) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
isHydrated.value = true;
return;
}
try {
const record = await getMyTrainingProgress(learnerTab.value);
hasWarnedLoadFailure.value = false;
applyProgressRecord(record);
} catch (error) {
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
if (error instanceof BusinessError && error.status === 401) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
return;
}
if (!hasWarnedLoadFailure.value) {
hasWarnedLoadFailure.value = true;
const message = error instanceof BusinessError
? error.message
: t('errors.generic');
msg.warning({
title: t('chat.training.errors.loadTitle'),
message: `${t('chat.training.errors.loadBody')}:${message}`,
});
}
applyProgressRecord(null);
} finally {
isHydrated.value = true;
}
};
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 {
const query = {
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),
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,
hasAuthenticatedUser,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
learnerTab,
],
([agent, loggedIn]) => {
if (!matchesTrainingAgent(agent)) {
records.value = [];
departmentOptions.value = [];
stats.value = {
total: 0,
passed: 0,
failed: 0,
inProgress: 0,
passRate: 0,
averageScore: 0,
};
return;
}
if (!loggedIn) {
hasWarnedLoadFailure.value = false;
applyProgressRecord(null);
isHydrated.value = true;
return;
}
isHydrated.value = false;
void loadTrainingConfig();
void loadTrainingProgress();
},
{ immediate: true },
);
watch(
[
isTrainingAgent,
isAdminViewer,
hrKeyword,
hrStatusFilter,
hrDepartmentFilter,
hrTypeFilter,
() => String(currentUser.value?.username || '').trim(),
() => String(currentUser.value?.role || '').trim(),
],
([enabled, canView]) => {
if (!enabled || !canView) return;
void loadAdminRecords();
},
{ immediate: true },
);
const markVideoCompleted = () => {
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
if (learnerTab.value === 'safety') {
checkAndAdvanceStage();
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;
}
stage.value = 'exam';
attemptCount.value += 1;
resetExamState();
void persistProgress();
};
/**
* 记录当前题答案;首次作答沿用自动推进,回看题目时则覆盖旧答案并实时重算分数。
* AI 触发时机:当员工在逐题考试阶段点击右侧题号返回某题时,需要允许直接改答且不破坏“提交答卷后才结算”的流程。
*/
const selectAnswer = (optionId: string) => {
if (!currentQuestion.value) return;
const answeredQuestion = currentQuestion.value;
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
selectedOptionId.value = optionId;
answerLocked.value = true;
const isCorrect = optionId === answeredQuestion.answer;
currentFeedbackCorrect.value = isCorrect;
const answerRecord: TrainingAnswerRecord = {
questionId: answeredQuestion.id,
selectedOptionId: optionId,
correct: isCorrect,
};
upsertAnswerRecord(answerRecord);
const nextScore = recalculateScoreFromAnswers(answerRecords.value);
score.value = nextScore;
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
// [STEP 1] 已答题被回看并改答时,停留在当前题,方便继续检查或跳到其他题。
if (hadExistingAnswer) {
void persistProgress();
return;
}
// [STEP 2] 最后一题首次答完后先停留在考试阶段,必须点击“提交答卷”才能进入结算结果。
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
void persistProgress();
return;
}
// [STEP 3] 首次作答且不是最后一题时,自动推进到下一题。
syncExamQuestionIndex(currentQuestionIndex.value + 1);
void persistProgress();
};
/**
* 进入下一题或结束考试。
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
*/
const moveToNextQuestion = () => {
if (!answerLocked.value) return;
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
return;
}
syncExamQuestionIndex(currentQuestionIndex.value + 1);
latestExamFeedback.value = null;
void persistProgress();
};
/**
* 统一提交整份答卷并进入结算结果。
* AI 触发时机:当员工已完成全部题目但尚未结算时,必须显式点击“提交答卷”后才允许进入第 4 阶段。
*/
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,
correctCount: answerRecords.value.filter((item) => item.correct).length,
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
isPassed: score.value >= passScore.value,
};
void persistProgress();
};
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;
if (nextStage === 'exam' && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
enterSafetyExam();
void persistProgress();
} else {
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,
});
};
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.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}%`,
];
return parts.join(';');
});
const learnerChatPrompt = computed(() => {
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
if (stage.value === 'result') {
return isPassed.value
? t('chat.training.chatPrompts.afterPass', { score: score.value })
: t('chat.training.chatPrompts.afterFail', { score: score.value });
}
return t('chat.training.chatPrompts.examInProgress', {
index: currentQuestionIndex.value + 1,
total: totalQuestionCount.value,
question: currentQuestion.value?.prompt || '',
});
});
/**
* 新建培训聊天会话时使用的统一提醒文案。
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
*/
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
passScore: passScore.value,
}));
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
const learnerAssistantMessage = computed(() => {
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
if (stage.value === 'video') {
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
}
if (stage.value === 'summary') {
return buildSummaryAssistantMessage();
}
if (stage.value === 'result') {
return isPassed.value
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
}
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
});
const showVideoModal = ref(false);
const currentViewingMaterialId = ref<number | null>(null);
const materialStartTime = ref<number>(0);
const currentViewingMaterialRequiredDuration = computed(() => {
if (!currentViewingMaterialId.value) return 0;
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === String(currentViewingMaterialId.value));
return resource?.requiredDuration || 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 = () => {
// Update legacy string fields to reflect real status based on resources
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
if (learnerTab.value === 'safety') {
const allSafetyCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
if (allSafetyCompleted && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
safetyStage.value = 'exam';
enterSafetyExam();
}
void persistProgress();
} else {
const activeStageMaterials = 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) {
stage.value = 'summary';
}
void persistProgress();
}
};
const videoUrl = computed(() => {
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();
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,
currentQuestion,
questionBank,
totalQuestionCount,
passScore,
answeredCount,
score,
attemptCount,
selectedOptionId,
answerLocked,
currentFeedbackCorrect,
examReadyToSubmit,
canEnterResultStage,
latestExamFeedback,
latestSettledResult,
answerRecords,
completionDate,
summaryPoints,
summaryChecklist,
learnerProgressPercent,
correctCount,
wrongCount,
isPassed,
currentUserName,
currentUserEmployeeId,
currentUserDepartment,
hrKeyword,
hrDepartmentFilter,
hrStatusFilter,
hrTypeFilter,
departmentOptions,
filteredRecords,
stats,
learnerChatPrompt,
newSessionReminderMessage,
shouldShowNewSessionReminder,
learnerAssistantMessage,
managementChatPrompt,
markVideoCompleted,
startExam,
selectAnswer,
syncExamQuestionIndex,
moveToNextQuestion,
submitExam,
restartExam,
setSafetyStage,
exportRecords,
showVideoModal,
videoUrl,
startMaterialTimer,
stopMaterialTimer,
currentViewingMaterialId,
currentViewingMaterialRequiredDuration,
currentTrainingAgentId,
};
}