481 lines
16 KiB
TypeScript
481 lines
16 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 {
|
||
exportTrainingRecords,
|
||
getMyTrainingProgress,
|
||
getTrainingStats,
|
||
listTrainingRecords,
|
||
saveMyTrainingProgress,
|
||
} from '@/features/chat/api/training.api';
|
||
import type {
|
||
TrainingAnswerRecord,
|
||
TrainingQuestion,
|
||
TrainingQuestionOption,
|
||
TrainingProgressRecord,
|
||
TrainingRecord,
|
||
TrainingRecordStatus,
|
||
TrainingStage,
|
||
TrainingStats,
|
||
TrainingWorkspaceView,
|
||
} from '@/features/chat/training/training.types';
|
||
|
||
type TrainingAgentLike = {
|
||
name?: string | null;
|
||
extra_config?: Record<string, unknown> | null;
|
||
} | null | undefined;
|
||
|
||
type TrainingUserLike = {
|
||
role?: string | null;
|
||
username?: string | null;
|
||
real_name?: string | null;
|
||
employee_id?: string | null;
|
||
department?: string | null;
|
||
} | null | undefined;
|
||
|
||
export interface UseTrainingWorkspaceOptions {
|
||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||
currentUser: ComputedRef<TrainingUserLike>;
|
||
pushLocalAssistantMessage?: (content: string) => Promise<void>;
|
||
pushLocalUserMessage?: (content: string) => Promise<void>;
|
||
}
|
||
|
||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||
|
||
/**
|
||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||
* AI 触发时机:当需要把培训 UI 只挂在指定 Agent 上时使用,优先读 extra_config 显式开关,避免误伤其他聊天场景。
|
||
*/
|
||
export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||
const extraConfig = agent?.extra_config || {};
|
||
const explicitFlags = [
|
||
extraConfig.training_workspace_enabled,
|
||
extraConfig.training_mode,
|
||
extraConfig.training_agent,
|
||
];
|
||
if (explicitFlags.some((value) => value === true || value === 'true')) {
|
||
return true;
|
||
}
|
||
const name = String(agent?.name || '').trim();
|
||
return TRAINING_AGENT_NAME_PATTERN.test(name);
|
||
}
|
||
|
||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||
|
||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||
const { t, tm } = useI18n();
|
||
|
||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||
const isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||
|
||
const stage = ref<TrainingStage>('video');
|
||
const currentQuestionIndex = ref(0);
|
||
const score = ref(0);
|
||
const attemptCount = ref(0);
|
||
const selectedOptionId = ref('');
|
||
const answerLocked = ref(false);
|
||
const currentFeedbackCorrect = ref(false);
|
||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||
const completionDate = ref<string | null>(null);
|
||
const currentJoinDate = ref<string | null>(null);
|
||
const isHydrated = ref(false);
|
||
|
||
const hrKeyword = ref('');
|
||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||
const hrDepartmentFilter = ref('all');
|
||
const records = ref<TrainingRecord[]>([]);
|
||
const departmentOptions = ref<string[]>([]);
|
||
const stats = ref<TrainingStats>({
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
});
|
||
let persistQueue: Promise<void> = Promise.resolve();
|
||
|
||
watch(isTrainingAgent, (enabled) => {
|
||
if (!enabled) {
|
||
activeView.value = 'learner';
|
||
isHydrated.value = false;
|
||
}
|
||
});
|
||
|
||
const summaryPoints = computed(() => {
|
||
const raw = tm('chat.training.summaryPoints');
|
||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||
});
|
||
|
||
const summaryChecklist = computed(() => {
|
||
const raw = tm('chat.training.summaryChecklist');
|
||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||
});
|
||
|
||
const rawQuestionBank = computed(() => {
|
||
const raw = tm('chat.training.questionBank');
|
||
return Array.isArray(raw) ? raw as Array<Record<string, unknown>> : [];
|
||
});
|
||
|
||
const booleanOptions = computed<TrainingQuestionOption[]>(() => {
|
||
const raw = tm('chat.training.booleanOptions');
|
||
if (!Array.isArray(raw)) return [];
|
||
return raw.map((item) => ({
|
||
id: String((item as Record<string, unknown>).id || ''),
|
||
label: String((item as Record<string, unknown>).label || ''),
|
||
}));
|
||
});
|
||
|
||
const questionBank = computed<TrainingQuestion[]>(() => rawQuestionBank.value.map((item) => {
|
||
const type = String(item.type || 'single') as TrainingQuestion['type'];
|
||
const rawOptions = Array.isArray(item.options) ? item.options : [];
|
||
const options = type === 'boolean'
|
||
? booleanOptions.value
|
||
: rawOptions.map((option) => ({
|
||
id: String((option as Record<string, unknown>).id || ''),
|
||
label: String((option as Record<string, unknown>).label || ''),
|
||
}));
|
||
|
||
return {
|
||
id: String(item.id || ''),
|
||
type,
|
||
prompt: String(item.prompt || ''),
|
||
answer: String(item.answer || ''),
|
||
explanation: String(item.explanation || ''),
|
||
options,
|
||
};
|
||
}));
|
||
|
||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||
const answeredCount = computed(() => answerRecords.value.length);
|
||
const correctCount = computed(() => answerRecords.value.filter((item) => item.correct).length);
|
||
const wrongCount = computed(() => answerRecords.value.filter((item) => !item.correct).length);
|
||
const isPassed = computed(() => score.value >= 90);
|
||
|
||
const learnerProgressPercent = computed(() => {
|
||
if (stage.value === 'video') return 25;
|
||
if (stage.value === 'summary') return 50;
|
||
if (stage.value === 'result') return 100;
|
||
const base = 50;
|
||
const examProgress = totalQuestionCount.value > 0
|
||
? Math.round((answeredCount.value / totalQuestionCount.value) * 50)
|
||
: 0;
|
||
return Math.min(100, base + examProgress);
|
||
});
|
||
|
||
const currentUserName = computed(() => (
|
||
String(currentUser.value?.real_name || '').trim()
|
||
|| String(currentUser.value?.username || '').trim()
|
||
|| t('chat.training.defaultLearnerName')
|
||
));
|
||
const currentUserEmployeeId = computed(() => String(currentUser.value?.employee_id || '').trim() || '--');
|
||
const currentUserDepartment = computed(() => String(currentUser.value?.department || '').trim() || t('chat.training.unknownDepartment'));
|
||
const filteredRecords = computed(() => records.value);
|
||
|
||
/**
|
||
* 重置考试状态,为首次开考或再次补考共用。
|
||
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
|
||
*/
|
||
const resetExamState = () => {
|
||
currentQuestionIndex.value = 0;
|
||
score.value = 0;
|
||
selectedOptionId.value = '';
|
||
answerLocked.value = false;
|
||
currentFeedbackCorrect.value = false;
|
||
answerRecords.value = [];
|
||
completionDate.value = null;
|
||
};
|
||
|
||
const syncAnswerStateForCurrentQuestion = () => {
|
||
const questionId = currentQuestion.value?.id;
|
||
const currentAnswer = questionId
|
||
? answerRecords.value.find((item) => item.questionId === questionId)
|
||
: null;
|
||
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
|
||
answerLocked.value = Boolean(currentAnswer);
|
||
currentFeedbackCorrect.value = Boolean(currentAnswer?.correct);
|
||
};
|
||
|
||
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
|
||
if (!record) {
|
||
stage.value = 'video';
|
||
resetExamState();
|
||
currentJoinDate.value = null;
|
||
return;
|
||
}
|
||
stage.value = record.stage;
|
||
currentQuestionIndex.value = record.currentQuestionIndex;
|
||
score.value = Number(record.score || 0);
|
||
attemptCount.value = Number(record.attempts || 0);
|
||
answerRecords.value = Array.isArray(record.answerDetails) ? record.answerDetails : [];
|
||
completionDate.value = record.completionDate;
|
||
currentJoinDate.value = record.joinDate || null;
|
||
syncAnswerStateForCurrentQuestion();
|
||
};
|
||
|
||
const buildProgressPayload = () => ({
|
||
stage: stage.value,
|
||
currentQuestionIndex: currentQuestionIndex.value,
|
||
score: score.value,
|
||
passed: isPassed.value,
|
||
attemptCount: attemptCount.value,
|
||
answerDetails: answerRecords.value,
|
||
joinDate: currentJoinDate.value || formatDate(new Date()),
|
||
});
|
||
|
||
const persistProgress = async () => {
|
||
if (!isTrainingAgent.value) return;
|
||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||
try {
|
||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||
completionDate.value = saved.completionDate;
|
||
if (isAdminViewer.value) {
|
||
void loadAdminRecords();
|
||
}
|
||
} catch {
|
||
// 保持本地培训流程可继续,避免接口波动阻断考试进行。
|
||
}
|
||
});
|
||
await persistQueue;
|
||
};
|
||
|
||
const loadTrainingProgress = async () => {
|
||
if (!isTrainingAgent.value) return;
|
||
try {
|
||
const record = await getMyTrainingProgress();
|
||
applyProgressRecord(record);
|
||
} catch {
|
||
applyProgressRecord(null);
|
||
} finally {
|
||
isHydrated.value = true;
|
||
}
|
||
};
|
||
|
||
const loadAdminRecords = async () => {
|
||
if (!isTrainingAgent.value || !isAdminViewer.value) return;
|
||
try {
|
||
const query = {
|
||
keyword: hrKeyword.value || undefined,
|
||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||
status: hrStatusFilter.value,
|
||
};
|
||
const [recordData, statsData] = await Promise.all([
|
||
listTrainingRecords(query),
|
||
getTrainingStats(query),
|
||
]);
|
||
records.value = recordData.items;
|
||
departmentOptions.value = recordData.departmentOptions;
|
||
stats.value = statsData;
|
||
} catch {
|
||
records.value = [];
|
||
departmentOptions.value = [];
|
||
stats.value = {
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
};
|
||
}
|
||
};
|
||
|
||
watch(currentAgent, (agent) => {
|
||
if (!matchesTrainingAgent(agent)) {
|
||
records.value = [];
|
||
departmentOptions.value = [];
|
||
stats.value = {
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
};
|
||
return;
|
||
}
|
||
isHydrated.value = false;
|
||
void loadTrainingProgress();
|
||
}, { immediate: true });
|
||
|
||
watch(
|
||
[isTrainingAgent, isAdminViewer, hrKeyword, hrStatusFilter, hrDepartmentFilter],
|
||
([enabled, canView]) => {
|
||
if (!enabled || !canView) return;
|
||
void loadAdminRecords();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
const markVideoCompleted = () => {
|
||
stage.value = 'summary';
|
||
// 立即推入本地助手消息(复盘卡片)
|
||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||
void persistProgress();
|
||
};
|
||
|
||
const startExam = () => {
|
||
stage.value = 'exam';
|
||
attemptCount.value += 1;
|
||
resetExamState();
|
||
// 立即推入第一题的消息引导
|
||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||
void persistProgress();
|
||
};
|
||
|
||
const selectAnswer = (optionId: string) => {
|
||
if (answerLocked.value || !currentQuestion.value) return;
|
||
selectedOptionId.value = optionId;
|
||
const isCorrect = optionId === currentQuestion.value.answer;
|
||
currentFeedbackCorrect.value = isCorrect;
|
||
if (isCorrect) {
|
||
score.value += 5;
|
||
}
|
||
answerRecords.value.push({
|
||
questionId: currentQuestion.value.id,
|
||
selectedOptionId: optionId,
|
||
correct: isCorrect,
|
||
});
|
||
answerLocked.value = true;
|
||
|
||
// 推入用户选择的答案到聊天流
|
||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||
void pushLocalUserMessage?.(label);
|
||
void persistProgress();
|
||
};
|
||
|
||
/**
|
||
* 进入下一题或结束考试。
|
||
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
|
||
*/
|
||
const moveToNextQuestion = () => {
|
||
if (!answerLocked.value) return;
|
||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||
stage.value = 'result';
|
||
completionDate.value = formatDate(new Date());
|
||
// 推入结果消息
|
||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
currentQuestionIndex.value += 1;
|
||
selectedOptionId.value = '';
|
||
answerLocked.value = false;
|
||
currentFeedbackCorrect.value = false;
|
||
// 推入下一题消息
|
||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||
void persistProgress();
|
||
};
|
||
|
||
const restartExam = () => {
|
||
stage.value = 'summary';
|
||
resetExamState();
|
||
// 重新推回复盘卡片
|
||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||
void persistProgress();
|
||
};
|
||
|
||
const exportRecords = async () => {
|
||
await exportTrainingRecords({
|
||
keyword: hrKeyword.value || undefined,
|
||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||
status: hrStatusFilter.value,
|
||
});
|
||
};
|
||
|
||
const managementChatPrompt = computed(() => {
|
||
const parts = [
|
||
t('chat.training.chatPrompts.hrSummaryPrefix'),
|
||
`${t('chat.training.hr.filters.keywordLabel')}: ${hrKeyword.value || t('chat.training.hr.filters.noLimit')}`,
|
||
`${t('chat.training.hr.filters.statusLabel')}: ${hrStatusFilter.value === 'all' ? t('chat.training.hr.filters.allStatuses') : t(`chat.training.hr.status.${hrStatusFilter.value}`)}`,
|
||
`${t('chat.training.hr.filters.departmentLabel')}: ${hrDepartmentFilter.value === 'all' ? t('chat.training.hr.filters.allDepartments') : hrDepartmentFilter.value}`,
|
||
`${t('chat.training.hr.stats.passRate')}: ${stats.value.passRate}%`,
|
||
];
|
||
return parts.join(';');
|
||
});
|
||
|
||
const learnerChatPrompt = computed(() => {
|
||
// 阶段 1:破冰与视频导学
|
||
if (stage.value === 'video') {
|
||
return `👋 欢迎加入公司!我是你的专属入职培训助手。今天的培训分为三个步骤:看视频 ➡️ 知识点复习 ➡️ 随堂测试(90分及格)。\n\n▶️ 请先点击观看 [入职培训视频]。观看完毕后,请回复【已看完】。`;
|
||
}
|
||
// 阶段 2:知识点串讲
|
||
if (stage.value === 'summary') {
|
||
return `${t('chat.training.chatPrompts.afterVideo')}\n\n参考知识点:\n${summaryPoints.value.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
|
||
}
|
||
// 阶段 4:结算
|
||
if (stage.value === 'result') {
|
||
return isPassed.value
|
||
? t('chat.training.chatPrompts.afterPass', { score: score.value })
|
||
: t('chat.training.chatPrompts.afterFail', { score: score.value });
|
||
}
|
||
// 阶段 3:互动测试
|
||
return t('chat.training.chatPrompts.examInProgress', {
|
||
index: currentQuestionIndex.value + 1,
|
||
total: totalQuestionCount.value,
|
||
question: currentQuestion.value?.prompt || '',
|
||
});
|
||
});
|
||
|
||
const showVideoModal = ref(false);
|
||
const videoUrl = computed(() => {
|
||
const extraConfig = currentAgent.value?.extra_config || {};
|
||
const customUrl = String(extraConfig.training_video_url || extraConfig.video_url || '').trim();
|
||
return customUrl || DEFAULT_TRAINING_VIDEO_URL;
|
||
});
|
||
|
||
return {
|
||
isTrainingAgent,
|
||
isAdminViewer,
|
||
isHydrated,
|
||
activeView,
|
||
stage,
|
||
currentQuestionIndex,
|
||
currentQuestion,
|
||
totalQuestionCount,
|
||
answeredCount,
|
||
score,
|
||
attemptCount,
|
||
selectedOptionId,
|
||
answerLocked,
|
||
currentFeedbackCorrect,
|
||
answerRecords,
|
||
completionDate,
|
||
summaryPoints,
|
||
summaryChecklist,
|
||
learnerProgressPercent,
|
||
correctCount,
|
||
wrongCount,
|
||
isPassed,
|
||
currentUserName,
|
||
currentUserEmployeeId,
|
||
currentUserDepartment,
|
||
hrKeyword,
|
||
hrStatusFilter,
|
||
hrDepartmentFilter,
|
||
departmentOptions,
|
||
filteredRecords,
|
||
stats,
|
||
learnerChatPrompt,
|
||
managementChatPrompt,
|
||
markVideoCompleted,
|
||
startExam,
|
||
selectAnswer,
|
||
moveToNextQuestion,
|
||
restartExam,
|
||
exportRecords,
|
||
showVideoModal,
|
||
videoUrl,
|
||
};
|
||
}
|