feat(员工培训): 完善新人入职培训聊天闭环交互
This commit is contained in:
1 parent
eb0466245b
commit
3f13bb5b46
19 files changed
+2975
-12
No files matched your search
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 Agent 的前端工作区状态,包括学员考试流、HR 统计筛选与 Excel 导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、xlsx,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,HR 端复用同页查看统计与导出。
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import * as XLSX from 'xlsx';
|
||||
import type {
|
||||
TrainingAnswerRecord,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingRecord,
|
||||
TrainingRecordStatus,
|
||||
TrainingStage,
|
||||
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 = /(培训|考试|入职)/;
|
||||
|
||||
/**
|
||||
* 判断当前 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);
|
||||
|
||||
const buildInitialRecords = (): TrainingRecord[] => [
|
||||
{
|
||||
id: 'r-001',
|
||||
name: '蔡晓晴',
|
||||
employeeId: 'HX10031',
|
||||
department: '人事部',
|
||||
joinDate: '2026-06-03',
|
||||
completionDate: '2026-06-05',
|
||||
score: 95,
|
||||
attempts: 1,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-002',
|
||||
name: '刘成',
|
||||
employeeId: 'HX10052',
|
||||
department: '制造部',
|
||||
joinDate: '2026-06-08',
|
||||
completionDate: '2026-06-10',
|
||||
score: 90,
|
||||
attempts: 2,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-003',
|
||||
name: '张艳',
|
||||
employeeId: 'HX10061',
|
||||
department: '品质部',
|
||||
joinDate: '2026-06-09',
|
||||
completionDate: null,
|
||||
score: 80,
|
||||
attempts: 1,
|
||||
status: 'failed',
|
||||
},
|
||||
{
|
||||
id: 'r-004',
|
||||
name: '陈立',
|
||||
employeeId: 'HX10077',
|
||||
department: '仓储部',
|
||||
joinDate: '2026-06-12',
|
||||
completionDate: '2026-06-14',
|
||||
score: 100,
|
||||
attempts: 1,
|
||||
status: 'passed',
|
||||
},
|
||||
{
|
||||
id: 'r-005',
|
||||
name: '吴佳',
|
||||
employeeId: 'HX10082',
|
||||
department: '业务部',
|
||||
joinDate: '2026-06-13',
|
||||
completionDate: null,
|
||||
score: null,
|
||||
attempts: 0,
|
||||
status: 'in_progress',
|
||||
},
|
||||
{
|
||||
id: 'r-006',
|
||||
name: '王腾',
|
||||
employeeId: 'HX10088',
|
||||
department: '工程部',
|
||||
joinDate: '2026-06-15',
|
||||
completionDate: '2026-06-18',
|
||||
score: 95,
|
||||
attempts: 3,
|
||||
status: 'passed',
|
||||
},
|
||||
];
|
||||
|
||||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const { currentAgent, currentUser, pushLocalAssistantMessage, pushLocalUserMessage } = options;
|
||||
const { t, tm } = useI18n();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const isAdminViewer = computed(() => currentUser.value?.role === 'admin');
|
||||
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 hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
const hrDepartmentFilter = ref('all');
|
||||
const records = ref<TrainingRecord[]>(buildInitialRecords());
|
||||
|
||||
watch(isTrainingAgent, (enabled) => {
|
||||
if (!enabled) {
|
||||
activeView.value = 'learner';
|
||||
}
|
||||
});
|
||||
|
||||
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 departmentOptions = computed(() => {
|
||||
const values = Array.from(new Set(records.value.map((item) => item.department))).sort((a, b) => a.localeCompare(b));
|
||||
return values;
|
||||
});
|
||||
|
||||
const filteredRecords = computed(() => {
|
||||
const keyword = hrKeyword.value.trim().toLowerCase();
|
||||
return records.value.filter((item) => {
|
||||
const matchesKeyword = !keyword
|
||||
|| item.name.toLowerCase().includes(keyword)
|
||||
|| item.employeeId.toLowerCase().includes(keyword);
|
||||
const matchesStatus = hrStatusFilter.value === 'all' || item.status === hrStatusFilter.value;
|
||||
const matchesDepartment = hrDepartmentFilter.value === 'all' || item.department === hrDepartmentFilter.value;
|
||||
return matchesKeyword && matchesStatus && matchesDepartment;
|
||||
});
|
||||
});
|
||||
|
||||
const stats = computed(() => {
|
||||
const total = records.value.length;
|
||||
const passed = records.value.filter((item) => item.status === 'passed').length;
|
||||
const failed = records.value.filter((item) => item.status === 'failed').length;
|
||||
const inProgress = records.value.filter((item) => item.status === 'in_progress').length;
|
||||
const averageScoreSource = records.value.filter((item) => typeof item.score === 'number');
|
||||
const averageScore = averageScoreSource.length > 0
|
||||
? Math.round(averageScoreSource.reduce((sum, item) => sum + Number(item.score || 0), 0) / averageScoreSource.length)
|
||||
: 0;
|
||||
return {
|
||||
total,
|
||||
passed,
|
||||
failed,
|
||||
inProgress,
|
||||
passRate: total > 0 ? Math.round((passed / total) * 100) : 0,
|
||||
averageScore,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 重置考试状态,为首次开考或再次补考共用。
|
||||
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
|
||||
*/
|
||||
const resetExamState = () => {
|
||||
currentQuestionIndex.value = 0;
|
||||
score.value = 0;
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
answerRecords.value = [];
|
||||
completionDate.value = null;
|
||||
};
|
||||
|
||||
const markVideoCompleted = () => {
|
||||
stage.value = 'summary';
|
||||
// 立即推入本地助手消息(复盘卡片)
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
stage.value = 'exam';
|
||||
attemptCount.value += 1;
|
||||
resetExamState();
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
/**
|
||||
* 进入下一题或结束考试。
|
||||
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
|
||||
*/
|
||||
const moveToNextQuestion = () => {
|
||||
if (!answerLocked.value) return;
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
upsertCurrentUserRecord();
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
return;
|
||||
}
|
||||
currentQuestionIndex.value += 1;
|
||||
selectedOptionId.value = '';
|
||||
answerLocked.value = false;
|
||||
currentFeedbackCorrect.value = false;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
stage.value = 'summary';
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
};
|
||||
|
||||
const upsertCurrentUserRecord = () => {
|
||||
const recordIndex = records.value.findIndex((item) => item.employeeId === currentUserEmployeeId.value);
|
||||
const existingRecord = recordIndex >= 0 ? records.value[recordIndex] : null;
|
||||
const nextRecord: TrainingRecord = {
|
||||
id: existingRecord?.id || `r-${Date.now()}`,
|
||||
name: currentUserName.value,
|
||||
employeeId: currentUserEmployeeId.value,
|
||||
department: currentUserDepartment.value,
|
||||
joinDate: existingRecord?.joinDate || formatDate(new Date()),
|
||||
completionDate: isPassed.value ? completionDate.value : null,
|
||||
score: score.value,
|
||||
attempts: attemptCount.value,
|
||||
status: isPassed.value ? 'passed' : 'failed',
|
||||
};
|
||||
if (recordIndex >= 0) {
|
||||
records.value.splice(recordIndex, 1, nextRecord);
|
||||
} else {
|
||||
records.value.unshift(nextRecord);
|
||||
}
|
||||
};
|
||||
|
||||
const exportRecords = () => {
|
||||
const rows = filteredRecords.value.map((item) => ({
|
||||
[t('chat.training.hr.columns.joinDate')]: item.joinDate,
|
||||
[t('chat.training.hr.columns.completionDate')]: item.completionDate || '--',
|
||||
[t('chat.training.hr.columns.department')]: item.department,
|
||||
[t('chat.training.hr.columns.name')]: item.name,
|
||||
[t('chat.training.hr.columns.employeeId')]: item.employeeId,
|
||||
[t('chat.training.hr.columns.score')]: item.score ?? '--',
|
||||
[t('chat.training.hr.columns.attempts')]: item.attempts,
|
||||
[t('chat.training.hr.columns.status')]: t(`chat.training.hr.status.${item.status}`),
|
||||
}));
|
||||
const worksheet = XLSX.utils.json_to_sheet(rows);
|
||||
const workbook = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, 'training');
|
||||
XLSX.writeFile(workbook, `training_records_${new Date().toISOString().slice(0, 10)}.xlsx`);
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
return {
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user