755 lines
27 KiB
TypeScript
755 lines
27 KiB
TypeScript
/**
|
||
* 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,
|
||
getMyTrainingProgress,
|
||
getTrainingStats,
|
||
listTrainingRecords,
|
||
saveMyTrainingProgress,
|
||
} from '@/features/chat/api/training.api';
|
||
import type {
|
||
TrainingAnswerRecord,
|
||
TrainingContentConfig,
|
||
TrainingExamTransitionFeedback,
|
||
TrainingQuestion,
|
||
TrainingQuestionOption,
|
||
TrainingProgressRecord,
|
||
TrainingRecord,
|
||
TrainingRecordStatus,
|
||
TrainingStage,
|
||
TrainingStats,
|
||
TrainingWorkspaceView,
|
||
} from '@/features/chat/training/training.types';
|
||
import {
|
||
matchesTrainingAgent,
|
||
resolveTrainingContentConfig,
|
||
resolveTrainingVideoGuide,
|
||
resolveTrainingVideoUrl,
|
||
type TrainingGuideLike,
|
||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||
|
||
type TrainingAgentLike = {
|
||
name?: string | null;
|
||
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;
|
||
|
||
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 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 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 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 hrKeyword = ref('');
|
||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||
const hrDepartmentFilter = ref('all');
|
||
const records = ref<TrainingRecord[]>([]);
|
||
const departmentOptions = ref<string[]>([]);
|
||
const stats = ref<TrainingStats>({
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
});
|
||
let persistQueue: Promise<void> = Promise.resolve();
|
||
|
||
watch(isTrainingAgent, (enabled) => {
|
||
if (!enabled) {
|
||
activeView.value = 'learner';
|
||
isHydrated.value = false;
|
||
}
|
||
});
|
||
|
||
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,
|
||
));
|
||
|
||
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
|
||
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
|
||
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
|
||
const passScore = computed(() => trainingContent.value.passScore);
|
||
|
||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||
const 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 learnerProgressPercent = computed(() => {
|
||
if (stage.value === 'video') return 25;
|
||
if (stage.value === 'summary') return 50;
|
||
if (stage.value === 'result') return 100;
|
||
const base = 50;
|
||
const examProgress = totalQuestionCount.value > 0
|
||
? Math.round((answeredCount.value / totalQuestionCount.value) * 50)
|
||
: 0;
|
||
return Math.min(100, base + examProgress);
|
||
});
|
||
|
||
const currentUserName = computed(() => (
|
||
String(currentUser.value?.real_name || '').trim()
|
||
|| String(currentUser.value?.username || '').trim()
|
||
|| t('chat.training.defaultLearnerName')
|
||
));
|
||
const currentUserEmployeeId = computed(() => String(currentUser.value?.employee_id || '').trim() || '--');
|
||
const currentUserDepartment = computed(() => String(currentUser.value?.department || '').trim() || t('chat.training.unknownDepartment'));
|
||
const filteredRecords = computed(() => records.value);
|
||
|
||
/**
|
||
* 重置考试状态,为首次开考或再次补考共用。
|
||
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
|
||
*/
|
||
const resetExamState = () => {
|
||
currentQuestionIndex.value = 0;
|
||
score.value = 0;
|
||
selectedOptionId.value = '';
|
||
answerLocked.value = false;
|
||
currentFeedbackCorrect.value = false;
|
||
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();
|
||
};
|
||
|
||
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
|
||
if (!record) {
|
||
stage.value = 'video';
|
||
resetExamState();
|
||
currentJoinDate.value = null;
|
||
latestSettledResult.value = null;
|
||
return;
|
||
}
|
||
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();
|
||
};
|
||
|
||
const buildProgressPayload = () => ({
|
||
stage: stage.value,
|
||
currentQuestionIndex: currentQuestionIndex.value,
|
||
score: score.value,
|
||
passed: isPassed.value,
|
||
attemptCount: attemptCount.value,
|
||
answerDetails: answerRecords.value,
|
||
joinDate: currentJoinDate.value || formatDate(new Date()),
|
||
});
|
||
|
||
const persistProgress = async () => {
|
||
if (!isTrainingAgent.value) return;
|
||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||
try {
|
||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||
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();
|
||
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 loadAdminRecords = async () => {
|
||
if (!isTrainingAgent.value || !isAdminViewer.value) return;
|
||
try {
|
||
const query = {
|
||
keyword: hrKeyword.value || undefined,
|
||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||
status: hrStatusFilter.value,
|
||
};
|
||
const [recordData, statsData] = await Promise.all([
|
||
listTrainingRecords(query),
|
||
getTrainingStats(query),
|
||
]);
|
||
records.value = recordData.items;
|
||
departmentOptions.value = recordData.departmentOptions;
|
||
stats.value = statsData;
|
||
} catch {
|
||
records.value = [];
|
||
departmentOptions.value = [];
|
||
stats.value = {
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
};
|
||
}
|
||
};
|
||
|
||
watch(
|
||
[
|
||
currentAgent,
|
||
hasAuthenticatedUser,
|
||
() => String(currentUser.value?.username || '').trim(),
|
||
() => String(currentUser.value?.role || '').trim(),
|
||
],
|
||
([agent, loggedIn]) => {
|
||
if (!matchesTrainingAgent(agent)) {
|
||
records.value = [];
|
||
departmentOptions.value = [];
|
||
stats.value = {
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
};
|
||
return;
|
||
}
|
||
if (!loggedIn) {
|
||
hasWarnedLoadFailure.value = false;
|
||
applyProgressRecord(null);
|
||
isHydrated.value = true;
|
||
return;
|
||
}
|
||
isHydrated.value = false;
|
||
void loadTrainingProgress();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
watch(
|
||
[
|
||
isTrainingAgent,
|
||
isAdminViewer,
|
||
hrKeyword,
|
||
hrStatusFilter,
|
||
hrDepartmentFilter,
|
||
() => String(currentUser.value?.username || '').trim(),
|
||
() => String(currentUser.value?.role || '').trim(),
|
||
],
|
||
([enabled, canView]) => {
|
||
if (!enabled || !canView) return;
|
||
void loadAdminRecords();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
const markVideoCompleted = () => {
|
||
stage.value = 'summary';
|
||
void persistProgress();
|
||
};
|
||
|
||
const startExam = () => {
|
||
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';
|
||
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 = () => {
|
||
stage.value = 'video';
|
||
resetExamState();
|
||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||
};
|
||
|
||
const exportRecords = async () => {
|
||
await exportTrainingRecords({
|
||
keyword: hrKeyword.value || undefined,
|
||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||
status: hrStatusFilter.value,
|
||
});
|
||
};
|
||
|
||
const managementChatPrompt = computed(() => {
|
||
const parts = [
|
||
t('chat.training.chatPrompts.hrSummaryPrefix'),
|
||
`${t('chat.training.hr.filters.keywordLabel')}: ${hrKeyword.value || t('chat.training.hr.filters.noLimit')}`,
|
||
`${t('chat.training.hr.filters.statusLabel')}: ${hrStatusFilter.value === 'all' ? t('chat.training.hr.filters.allStatuses') : t(`chat.training.hr.status.${hrStatusFilter.value}`)}`,
|
||
`${t('chat.training.hr.filters.departmentLabel')}: ${hrDepartmentFilter.value === 'all' ? t('chat.training.hr.filters.allDepartments') : hrDepartmentFilter.value}`,
|
||
`${t('chat.training.hr.stats.passRate')}: ${stats.value.passRate}%`,
|
||
];
|
||
return parts.join(';');
|
||
});
|
||
|
||
const learnerChatPrompt = computed(() => {
|
||
// 发送给 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 videoUrl = computed(() => {
|
||
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
|
||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
|
||
});
|
||
|
||
return {
|
||
isTrainingAgent,
|
||
isAdminViewer,
|
||
isHydrated,
|
||
activeView,
|
||
stage,
|
||
currentQuestionIndex,
|
||
currentQuestionNumber,
|
||
currentQuestion,
|
||
totalQuestionCount,
|
||
passScore,
|
||
answeredCount,
|
||
score,
|
||
attemptCount,
|
||
selectedOptionId,
|
||
answerLocked,
|
||
currentFeedbackCorrect,
|
||
examReadyToSubmit,
|
||
canEnterResultStage,
|
||
latestExamFeedback,
|
||
latestSettledResult,
|
||
answerRecords,
|
||
completionDate,
|
||
summaryPoints,
|
||
summaryChecklist,
|
||
learnerProgressPercent,
|
||
correctCount,
|
||
wrongCount,
|
||
isPassed,
|
||
currentUserName,
|
||
currentUserEmployeeId,
|
||
currentUserDepartment,
|
||
hrKeyword,
|
||
hrStatusFilter,
|
||
hrDepartmentFilter,
|
||
departmentOptions,
|
||
filteredRecords,
|
||
stats,
|
||
learnerChatPrompt,
|
||
newSessionReminderMessage,
|
||
shouldShowNewSessionReminder,
|
||
learnerAssistantMessage,
|
||
managementChatPrompt,
|
||
markVideoCompleted,
|
||
startExam,
|
||
selectAnswer,
|
||
syncExamQuestionIndex,
|
||
moveToNextQuestion,
|
||
submitExam,
|
||
restartExam,
|
||
exportRecords,
|
||
showVideoModal,
|
||
videoUrl,
|
||
};
|
||
}
|