427 lines
16 KiB
TypeScript
427 lines
16 KiB
TypeScript
/**
|
|
* 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 {
|
|
SafetyProgressState,
|
|
TrainingAnswerRecord,
|
|
TrainingExamMode,
|
|
TrainingProgressRecord,
|
|
TrainingPublishedConfig,
|
|
TrainingRecord,
|
|
TrainingStage,
|
|
TrainingStats,
|
|
LeanTrainingDashboard,
|
|
LeanTrainingDashboardRow,
|
|
LeanTrainingMyTask,
|
|
LeanTrainingTaskStatus,
|
|
LeanTrainingWeeklyTask,
|
|
TrainingType,
|
|
TrainingTypeOption,
|
|
} from '../training/training.types';
|
|
|
|
type LeanTrainingTaskApi = {
|
|
id: number; week_key: string; due_at: string; video_resource_ids: number[];
|
|
target_roles: string[]; target_user_ids: number[];
|
|
videos: Array<{ id: number; name: string; file_url?: string | null }>; status: string; min_summary_length: number;
|
|
weekly_count?: number; pushed_video_count?: number;
|
|
week_end?: string | null; week_index?: number;
|
|
};
|
|
|
|
type LeanTrainingMyTaskApi = LeanTrainingTaskApi & {
|
|
task_status: LeanTrainingTaskStatus;
|
|
completion: { summary_text: string; watched_at: Record<string, string>; completed_at?: string | null } | null;
|
|
};
|
|
|
|
type LeanTrainingDashboardRowApi = {
|
|
id?: number; user_id: number; employee_id?: string | null; name: string; department?: string | null;
|
|
videos: Array<{ name: string; watched_at?: string | null }>;
|
|
// 后端序列化层三态归一:completed=已提交感悟;overdue=过截止未完成;in_progress=进行中
|
|
summary_text?: string | null; status: 'completed' | 'in_progress' | 'overdue'; completed_at?: string | null;
|
|
};
|
|
|
|
const mapLeanTask = (data: LeanTrainingTaskApi): LeanTrainingWeeklyTask => ({
|
|
id: data.id, weekKey: data.week_key, dueAt: data.due_at, videoResourceIds: data.video_resource_ids || [],
|
|
targetRoles: data.target_roles || [], targetUserIds: data.target_user_ids || [],
|
|
videos: (data.videos || []).map((video) => ({ id: video.id, name: video.name, fileUrl: video.file_url || null })),
|
|
status: data.status, minSummaryLength: data.min_summary_length,
|
|
weeklyCount: data.weekly_count, pushedVideoCount: data.pushed_video_count,
|
|
weekEnd: data.week_end ?? null, weekIndex: data.week_index,
|
|
});
|
|
|
|
const mapLeanMyTask = (data: LeanTrainingMyTaskApi): LeanTrainingMyTask => ({
|
|
...mapLeanTask(data),
|
|
taskStatus: data.task_status,
|
|
completion: data.completion ? {
|
|
summaryText: data.completion.summary_text,
|
|
watchedAt: data.completion.watched_at || {},
|
|
completedAt: data.completion.completed_at || null,
|
|
} : null,
|
|
});
|
|
|
|
const mapLeanDashboardRow = (data: LeanTrainingDashboardRowApi): LeanTrainingDashboardRow => ({
|
|
id: data.id, userId: data.user_id, employeeId: data.employee_id, name: data.name, department: data.department,
|
|
videos: (data.videos || []).map((item) => ({ name: item.name, watchedAt: item.watched_at })),
|
|
summaryText: data.summary_text, status: data.status, completedAt: data.completed_at,
|
|
});
|
|
|
|
type TrainingRecordApi = {
|
|
id: number;
|
|
user_id?: number;
|
|
training_type?: TrainingType;
|
|
training_version?: string | null;
|
|
exam_mode?: TrainingExamMode;
|
|
safety_stage?: string | null;
|
|
safety_progress?: Partial<SafetyProgressState> | null;
|
|
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;
|
|
answer_text?: string;
|
|
correct?: boolean;
|
|
score_ratio?: number;
|
|
}>;
|
|
completion_time?: string | null;
|
|
updated_at?: string | null;
|
|
started_at?: string | null;
|
|
status?: TrainingRecord['status'];
|
|
};
|
|
|
|
type TrainingConfigApi = {
|
|
id: number;
|
|
training_type?: TrainingType;
|
|
version?: string | null;
|
|
pass_score?: number | null;
|
|
settings?: Record<string, unknown> | null;
|
|
resources?: Array<{
|
|
id?: number | null;
|
|
resource_type?: string | null;
|
|
training_level?: 'company' | 'department' | 'team' | null;
|
|
agent_guide_id?: number | null;
|
|
inline_questions?: unknown[];
|
|
title?: string | null;
|
|
sort_order?: number;
|
|
required_duration?: number;
|
|
resource?: {
|
|
id?: number;
|
|
file_name?: string;
|
|
file_type?: string;
|
|
file_url?: string;
|
|
guide_usage?: string;
|
|
source_file_name?: string;
|
|
} | null;
|
|
}>;
|
|
};
|
|
|
|
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?: string;
|
|
type?: string;
|
|
page?: number;
|
|
page_size?: number;
|
|
}
|
|
|
|
export interface SaveTrainingProgressPayload {
|
|
stage: TrainingStage;
|
|
agentId?: number | null;
|
|
trainingVersion?: string | null;
|
|
examMode?: TrainingExamMode;
|
|
safetyStage?: string | null;
|
|
safetyProgress?: Partial<SafetyProgressState> | null;
|
|
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 || ''),
|
|
answerText: String(item.answer_text || ''),
|
|
correct: Boolean(item.correct),
|
|
scoreRatio: Number(item.score_ratio || 0),
|
|
}))
|
|
: [];
|
|
}
|
|
|
|
function mapSafetyProgressState(items?: TrainingRecordApi['safety_progress']): SafetyProgressState {
|
|
return {
|
|
company: String(items?.company || 'pending'),
|
|
department: String(items?.department || 'pending'),
|
|
team: String(items?.team || 'pending'),
|
|
resource_progress: (items as any)?.resource_progress || {},
|
|
};
|
|
}
|
|
|
|
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
|
|
return {
|
|
id: data.id,
|
|
trainingType: data.training_type || 'onboarding',
|
|
trainingVersion: data.training_version || undefined,
|
|
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,
|
|
examMode: (data.exam_mode || 'unified') as TrainingExamMode,
|
|
safetyStage: data.safety_stage ? String(data.safety_stage) as TrainingProgressRecord['safetyStage'] : null,
|
|
safetyProgress: mapSafetyProgressState(data.safety_progress),
|
|
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 mapTrainingConfig(data: TrainingConfigApi): TrainingPublishedConfig {
|
|
return {
|
|
id: data.id,
|
|
trainingType: data.training_type || 'onboarding',
|
|
version: String(data.version || ''),
|
|
passScore: Number(data.pass_score || 0),
|
|
settings: data.settings || {},
|
|
resources: Array.isArray(data.resources)
|
|
? data.resources.map((resource) => ({
|
|
id: resource.id,
|
|
resourceType: resource.resource_type,
|
|
trainingLevel: resource.training_level,
|
|
agentGuideId: resource.agent_guide_id,
|
|
inlineQuestions: resource.inline_questions,
|
|
title: resource.title,
|
|
sortOrder: Number(resource.sort_order || 0),
|
|
requiredDuration: Number(resource.required_duration || 0),
|
|
resource: resource.resource ? {
|
|
id: resource.resource.id,
|
|
fileName: resource.resource.file_name || resource.resource.source_file_name,
|
|
fileType: resource.resource.file_type,
|
|
fileUrl: resource.resource.file_url,
|
|
guideUsage: resource.resource.guide_usage,
|
|
} : null,
|
|
}))
|
|
: [],
|
|
};
|
|
}
|
|
|
|
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
|
const progress = mapTrainingProgressRecord(data);
|
|
return {
|
|
id: progress.id,
|
|
trainingType: progress.trainingType,
|
|
trainingVersion: progress.trainingVersion,
|
|
name: progress.name,
|
|
employeeId: progress.employeeId,
|
|
department: progress.department,
|
|
joinDate: progress.joinDate,
|
|
completionDate: progress.completionDate,
|
|
score: progress.score,
|
|
attempts: progress.attempts,
|
|
status: progress.status,
|
|
answerDetails: progress.answerDetails,
|
|
};
|
|
}
|
|
|
|
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.type) params.set('type', query.type);
|
|
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 getMyTrainingTypes(): Promise<TrainingTypeOption[]> {
|
|
return requestJson<TrainingTypeOption[]>('/api/user/training-types', authHeaders());
|
|
}
|
|
|
|
export async function getMyLeanTrainingTasks(): Promise<LeanTrainingMyTask[]> {
|
|
const response = await requestJson<LeanTrainingMyTaskApi[]>('/api/user/lean-training/my-tasks', authHeaders());
|
|
return (response || []).map(mapLeanMyTask);
|
|
}
|
|
|
|
export async function markMyLeanVideoWatched(weeklyTaskId: number, resourceId: number): Promise<void> {
|
|
await requestJson<{ watched_at: Record<string, string> }>('/api/user/lean-training/my-tasks/watched', {
|
|
method: 'POST',
|
|
...jsonAuthHeaders(),
|
|
body: JSON.stringify({ weekly_task_id: weeklyTaskId, resource_id: resourceId }),
|
|
});
|
|
}
|
|
|
|
export async function saveMyLeanTrainingCompletion(payload: { weeklyTaskId: number; watchedAt: Record<string, string>; summaryText: string }): Promise<LeanTrainingDashboardRow> {
|
|
const response = await requestJson<LeanTrainingDashboardRowApi>('/api/user/lean-training/completions', {
|
|
method: 'PUT', ...jsonAuthHeaders(), body: JSON.stringify({ weekly_task_id: payload.weeklyTaskId, watched_at: payload.watchedAt, summary_text: payload.summaryText }),
|
|
});
|
|
return mapLeanDashboardRow(response);
|
|
}
|
|
|
|
export async function getLeanTrainingDashboard(taskId?: number): Promise<LeanTrainingDashboard> {
|
|
// task_id 为空时后端返回最新一期;periods 为全部期次摘要(期号按周次升序),供管理端下拉切换第几期。
|
|
const query = taskId ? `?task_id=${taskId}` : '';
|
|
const response = await requestJson<{ task: LeanTrainingTaskApi | null; completed: LeanTrainingDashboardRowApi[]; incomplete: LeanTrainingDashboardRowApi[]; periods?: Array<{ id: number; week_key: string; index: number }> }>(`/api/admin/lean-training/dashboard${query}`, authHeaders());
|
|
return {
|
|
task: response.task ? mapLeanTask(response.task) : null,
|
|
completed: (response.completed || []).map(mapLeanDashboardRow),
|
|
incomplete: (response.incomplete || []).map(mapLeanDashboardRow),
|
|
periods: (response.periods || []).map((period) => ({ id: period.id, weekKey: period.week_key, index: period.index })),
|
|
};
|
|
}
|
|
|
|
export async function exportLeanTrainingDashboard(taskId: number): Promise<void> {
|
|
const response = await fetch(`/api/admin/lean-training/dashboard/export?task_id=${taskId}`, {
|
|
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 = `lean_training_dashboard_${new Date().toISOString().slice(0, 10)}.xlsx`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
link.remove();
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
/** HR 对指定成员发起精益培训定向提醒;返回后端实发统计(sent/failed 才是真实送达情况,created 含发送失败)。 */
|
|
export async function sendLeanTrainingReminders(weeklyTaskId: number, userIds: number[]): Promise<{ created: number; sent: number; skipped: number; failed: number }> {
|
|
return requestJson<{ created: number; sent: number; skipped: number; failed: number }>(`/api/admin/lean-training/weekly-tasks/${weeklyTaskId}/reminders`, {
|
|
method: 'POST',
|
|
...jsonAuthHeaders(),
|
|
body: JSON.stringify({ user_ids: userIds }),
|
|
});
|
|
}
|
|
|
|
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
|
|
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${encodeURIComponent(type)}`, authHeaders());
|
|
return data ? mapTrainingProgressRecord(data) : null;
|
|
}
|
|
|
|
export async function getMyTrainingConfig(type: string = 'onboarding'): Promise<TrainingPublishedConfig | null> {
|
|
const data = await requestJson<TrainingConfigApi | null>(`/api/user/training-config?type=${encodeURIComponent(type)}`, authHeaders());
|
|
return data ? mapTrainingConfig(data) : null;
|
|
}
|
|
|
|
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload, type: string = 'onboarding'): Promise<TrainingProgressRecord> {
|
|
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
|
|
method: 'PUT',
|
|
...jsonAuthHeaders(),
|
|
body: JSON.stringify({
|
|
agent_id: payload.agentId || undefined,
|
|
stage: payload.stage,
|
|
training_version: payload.trainingVersion || undefined,
|
|
exam_mode: payload.examMode || undefined,
|
|
safety_stage: payload.safetyStage || undefined,
|
|
safety_progress: payload.safetyProgress || undefined,
|
|
current_question_index: payload.currentQuestionIndex,
|
|
score: payload.score,
|
|
passed: payload.passed,
|
|
attempt_count: payload.attemptCount,
|
|
type: type,
|
|
answer_details: payload.answerDetails.map((item) => ({
|
|
question_id: item.questionId,
|
|
selected_option_id: item.selectedOptionId,
|
|
answer_text: item.answerText || '',
|
|
correct: item.correct,
|
|
score_ratio: item.scoreRatio || 0,
|
|
})),
|
|
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);
|
|
}
|