feat(training): 打通新人培训真实数据闭环
This commit is contained in:
1 parent
3f13bb5b46
commit
19f43e8018
13 files changed
+1144
-162
No files matched your search
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* features/chat/api/training.api.ts
|
||||
* 用途:培训工作区专用 HTTP API,负责员工进度读取/保存、HR 记录查询、统计和导出。
|
||||
* 依赖:shared/api/client、auth headers、training.types。
|
||||
* 逻辑:把后端 training 领域的 snake_case 返回值统一映射成前端工作区需要的 camelCase 结构。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
|
||||
|
||||
type TrainingRecordApi = {
|
||||
id: number;
|
||||
user_id?: number;
|
||||
employee_id?: string | null;
|
||||
name?: string | null;
|
||||
department?: string | null;
|
||||
join_date?: string | null;
|
||||
stage?: TrainingStage;
|
||||
current_question_index?: number;
|
||||
score?: number;
|
||||
passed?: boolean;
|
||||
attempt_count?: number;
|
||||
answer_details?: Array<{
|
||||
question_id?: string;
|
||||
selected_option_id?: string;
|
||||
correct?: boolean;
|
||||
}>;
|
||||
completion_time?: string | null;
|
||||
updated_at?: string | null;
|
||||
started_at?: string | null;
|
||||
status?: TrainingRecord['status'];
|
||||
};
|
||||
|
||||
type TrainingListApi = {
|
||||
items: TrainingRecordApi[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
pages: number;
|
||||
department_options: string[];
|
||||
};
|
||||
|
||||
type TrainingStatsApi = {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
in_progress: number;
|
||||
pass_rate: number;
|
||||
average_score: number;
|
||||
};
|
||||
|
||||
export interface TrainingRecordQuery {
|
||||
keyword?: string;
|
||||
department?: string;
|
||||
status?: 'all' | 'passed' | 'failed' | 'in_progress';
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface SaveTrainingProgressPayload {
|
||||
stage: TrainingStage;
|
||||
currentQuestionIndex: number;
|
||||
score: number;
|
||||
passed: boolean;
|
||||
attemptCount: number;
|
||||
answerDetails: TrainingAnswerRecord[];
|
||||
joinDate?: string | null;
|
||||
}
|
||||
|
||||
const authHeaders = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuthHeaders = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): TrainingAnswerRecord[] {
|
||||
return Array.isArray(items)
|
||||
? items.map((item) => ({
|
||||
questionId: String(item.question_id || ''),
|
||||
selectedOptionId: String(item.selected_option_id || ''),
|
||||
correct: Boolean(item.correct),
|
||||
}))
|
||||
: [];
|
||||
}
|
||||
|
||||
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
|
||||
return {
|
||||
id: data.id,
|
||||
name: String(data.name || ''),
|
||||
employeeId: String(data.employee_id || ''),
|
||||
department: String(data.department || ''),
|
||||
joinDate: String(data.join_date || ''),
|
||||
completionDate: data.completion_time ? String(data.completion_time).slice(0, 10) : null,
|
||||
score: typeof data.score === 'number' ? data.score : null,
|
||||
attempts: Number(data.attempt_count || 0),
|
||||
status: data.status || 'in_progress',
|
||||
stage: (data.stage || 'video') as TrainingStage,
|
||||
currentQuestionIndex: Number(data.current_question_index || 0),
|
||||
passed: Boolean(data.passed),
|
||||
answerDetails: mapAnswerDetails(data.answer_details),
|
||||
startedAt: data.started_at || null,
|
||||
completionTime: data.completion_time || null,
|
||||
updatedAt: data.updated_at || null,
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
||||
const progress = mapTrainingProgressRecord(data);
|
||||
return {
|
||||
id: progress.id,
|
||||
name: progress.name,
|
||||
employeeId: progress.employeeId,
|
||||
department: progress.department,
|
||||
joinDate: progress.joinDate,
|
||||
completionDate: progress.completionDate,
|
||||
score: progress.score,
|
||||
attempts: progress.attempts,
|
||||
status: progress.status,
|
||||
};
|
||||
}
|
||||
|
||||
function buildQueryString(query: TrainingRecordQuery = {}) {
|
||||
const params = new URLSearchParams();
|
||||
if (query.keyword) params.set('keyword', query.keyword);
|
||||
if (query.department) params.set('department', query.department);
|
||||
if (query.status) params.set('status', query.status);
|
||||
if (query.page) params.set('page', String(query.page));
|
||||
if (query.page_size) params.set('page_size', String(query.page_size));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
|
||||
return data ? mapTrainingProgressRecord(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
|
||||
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
|
||||
method: 'PUT',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
stage: payload.stage,
|
||||
current_question_index: payload.currentQuestionIndex,
|
||||
score: payload.score,
|
||||
passed: payload.passed,
|
||||
attempt_count: payload.attemptCount,
|
||||
answer_details: payload.answerDetails.map((item) => ({
|
||||
question_id: item.questionId,
|
||||
selected_option_id: item.selectedOptionId,
|
||||
correct: item.correct,
|
||||
})),
|
||||
join_date: payload.joinDate || undefined,
|
||||
}),
|
||||
});
|
||||
return mapTrainingProgressRecord(data);
|
||||
}
|
||||
|
||||
export async function listTrainingRecords(query: TrainingRecordQuery = {}) {
|
||||
const qs = buildQueryString(query);
|
||||
const data = await requestJson<TrainingListApi>(`/api/admin/training-records${qs ? `?${qs}` : ''}`, authHeaders());
|
||||
return {
|
||||
items: data.items.map(mapTrainingRecord),
|
||||
total: data.total,
|
||||
page: data.page,
|
||||
pageSize: data.page_size,
|
||||
pages: data.pages,
|
||||
departmentOptions: data.department_options || [],
|
||||
};
|
||||
}
|
||||
|
||||
export async function getTrainingStats(query: TrainingRecordQuery = {}): Promise<TrainingStats> {
|
||||
const qs = buildQueryString(query);
|
||||
const data = await requestJson<TrainingStatsApi>(`/api/admin/training-records/stats${qs ? `?${qs}` : ''}`, authHeaders());
|
||||
return {
|
||||
total: Number(data.total || 0),
|
||||
passed: Number(data.passed || 0),
|
||||
failed: Number(data.failed || 0),
|
||||
inProgress: Number(data.in_progress || 0),
|
||||
passRate: Number(data.pass_rate || 0),
|
||||
averageScore: Number(data.average_score || 0),
|
||||
};
|
||||
}
|
||||
|
||||
export async function exportTrainingRecords(query: TrainingRecordQuery = {}): Promise<void> {
|
||||
const qs = buildQueryString(query);
|
||||
const response = await fetch(`/api/admin/training-records/export${qs ? `?${qs}` : ''}`, {
|
||||
method: 'GET',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Export failed: HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `training_records_${new Date().toISOString().slice(0, 10)}.xlsx`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
@@ -109,7 +109,7 @@ const currentAnswerLabel = computed(() => {
|
||||
const workspaceExpanded = ref(false);
|
||||
|
||||
const autoSyncInitialPrompt = () => {
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
if (workspace.isTrainingAgent && workspace.isHydrated && !props.hasMessages) {
|
||||
emit('push-local-assistant-message', workspace.learnerChatPrompt);
|
||||
}
|
||||
};
|
||||
@@ -121,16 +121,6 @@ watch(
|
||||
userExpandedOverride.value = false;
|
||||
workspaceExpanded.value = false;
|
||||
emit('update:expanded', false);
|
||||
|
||||
// 切换 Agent 后,如果是培训 Agent 且没有消息,立即触发引导
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
// 给予极短延迟确保其它状态同步完成
|
||||
setTimeout(() => {
|
||||
if (workspace.isTrainingAgent && !props.hasMessages) {
|
||||
autoSyncInitialPrompt();
|
||||
}
|
||||
}, 300);
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
@@ -143,6 +133,15 @@ watch(() => props.hasMessages, () => {
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => workspace.isHydrated,
|
||||
(ready) => {
|
||||
if (ready && workspace.isTrainingAgent && !props.hasMessages) {
|
||||
autoSyncInitialPrompt();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const isCompactMode = computed(() => !workspaceExpanded.value);
|
||||
|
||||
const compactSummary = computed(() => {
|
||||
@@ -803,7 +802,6 @@ const compactSummary = computed(() => {
|
||||
</button>
|
||||
<div class="aspect-video bg-black">
|
||||
<video
|
||||
ref="videoPlayer"
|
||||
controls
|
||||
autoplay
|
||||
class="h-full w-full"
|
||||
@@ -811,7 +809,7 @@ const compactSummary = computed(() => {
|
||||
@seeking="handleVideoSeeking"
|
||||
@ended="handleVideoEnded"
|
||||
>
|
||||
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
|
||||
<source :src="workspace.videoUrl" type="video/mp4">
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
</div>
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export interface TrainingAnswerRecord {
|
||||
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
|
||||
|
||||
export interface TrainingRecord {
|
||||
id: string;
|
||||
id: string | number;
|
||||
name: string;
|
||||
employeeId: string;
|
||||
department: string;
|
||||
@@ -44,3 +44,22 @@ export interface TrainingRecord {
|
||||
attempts: number;
|
||||
status: TrainingRecordStatus;
|
||||
}
|
||||
|
||||
export interface TrainingProgressRecord extends TrainingRecord {
|
||||
stage: TrainingStage;
|
||||
currentQuestionIndex: number;
|
||||
passed: boolean;
|
||||
answerDetails: TrainingAnswerRecord[];
|
||||
startedAt: string | null;
|
||||
completionTime: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export interface TrainingStats {
|
||||
total: number;
|
||||
passed: number;
|
||||
failed: number;
|
||||
inProgress: number;
|
||||
passRate: number;
|
||||
averageScore: number;
|
||||
}
|
||||
Reference in new issue
Block a user