feat(training): 打通新人培训真实数据闭环
This commit is contained in:
1 parent
3f13bb5b46
commit
19f43e8018
13 files changed
+1144
-162
No files matched your search
@@ -1,19 +1,27 @@
|
||||
/**
|
||||
* features/chat/composables/useTrainingWorkspace.ts
|
||||
* 用途:封装新人培训 Agent 的前端工作区状态,包括学员考试流、HR 统计筛选与 Excel 导出。
|
||||
* 依赖:Vue reactivity、vue-i18n、xlsx,以及 training.types。
|
||||
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,HR 端复用同页查看统计与导出。
|
||||
* 用途:封装新人培训 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 * as XLSX from 'xlsx';
|
||||
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';
|
||||
|
||||
@@ -38,6 +46,7 @@ export interface UseTrainingWorkspaceOptions {
|
||||
}
|
||||
|
||||
const TRAINING_AGENT_NAME_PATTERN = /(培训|考试|入职)/;
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用“培训工作区”。
|
||||
@@ -59,81 +68,12 @@ export function matchesTrainingAgent(agent: TrainingAgentLike): boolean {
|
||||
|
||||
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 isAdminViewer = computed(() => ['admin', 'hr'].includes(String(currentUser.value?.role || '')));
|
||||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
@@ -145,15 +85,28 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
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[]>(buildInitialRecords());
|
||||
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;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -226,42 +179,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
));
|
||||
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,
|
||||
};
|
||||
});
|
||||
const filteredRecords = computed(() => records.value);
|
||||
|
||||
/**
|
||||
* 重置考试状态,为首次开考或再次补考共用。
|
||||
@@ -277,10 +195,133 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
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 = () => {
|
||||
@@ -289,6 +330,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
resetExamState();
|
||||
// 立即推入第一题的消息引导
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const selectAnswer = (optionId: string) => {
|
||||
@@ -309,6 +351,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
// 推入用户选择的答案到聊天流
|
||||
const label = currentQuestion.value.options?.find(o => o.id === optionId)?.label || optionId;
|
||||
void pushLocalUserMessage?.(label);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -320,9 +363,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||||
stage.value = 'result';
|
||||
completionDate.value = formatDate(new Date());
|
||||
upsertCurrentUserRecord();
|
||||
// 推入结果消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
currentQuestionIndex.value += 1;
|
||||
@@ -331,6 +374,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentFeedbackCorrect.value = false;
|
||||
// 推入下一题消息
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
@@ -338,44 +382,15 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
resetExamState();
|
||||
// 重新推回复盘卡片
|
||||
void pushLocalAssistantMessage?.(learnerChatPrompt.value);
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
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 exportRecords = async () => {
|
||||
await exportTrainingRecords({
|
||||
keyword: hrKeyword.value || undefined,
|
||||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||||
status: hrStatusFilter.value,
|
||||
});
|
||||
};
|
||||
|
||||
const managementChatPrompt = computed(() => {
|
||||
@@ -413,10 +428,16 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -454,5 +475,6 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
restartExam,
|
||||
exportRecords,
|
||||
showVideoModal,
|
||||
videoUrl,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user