- 后端:新增周任务视频推送服务与定时任务,新增模型迁移 fb26bc033d27 - 配置:WECOM_NOTIFY_EVENTS 追加 training_lean_video_push 事件(dev/test/prod/shared 同步) - 管理端:培训配置页新增定向目标弹窗 LeanTargetModal - 工作台:完成看板提醒按钮按 sent/failed 实发统计如实提示(部分成功/失败/未发送),避免企微发送失败误报成功 - 文档:更新功能清单与技术架构,新增精益管理周任务规则手册;四语言 i18n 同步补齐
1389 lines
56 KiB
TypeScript
1389 lines
56 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 { BusinessError } from '@/shared/api/client';
|
||
import { useMessage } from '@/shared/composables/useMessage';
|
||
import {
|
||
exportTrainingRecords,
|
||
getMyTrainingConfig,
|
||
getMyTrainingProgress,
|
||
getMyTrainingTypes,
|
||
getTrainingStats,
|
||
getMyLeanTrainingTasks,
|
||
getLeanTrainingDashboard,
|
||
sendLeanTrainingReminders,
|
||
listTrainingRecords,
|
||
markMyLeanVideoWatched,
|
||
saveMyTrainingProgress,
|
||
saveMyLeanTrainingCompletion,
|
||
} from '@/features/chat/api/training.api';
|
||
import type {
|
||
SafetyProgressState,
|
||
TrainingAnswerRecord,
|
||
TrainingContentConfig,
|
||
TrainingExamMode,
|
||
TrainingExamTransitionFeedback,
|
||
TrainingQuestion,
|
||
TrainingQuestionOption,
|
||
TrainingProgressRecord,
|
||
TrainingPublishedConfig,
|
||
TrainingRecord,
|
||
TrainingRecordStatus,
|
||
SafetyStage,
|
||
TrainingStage,
|
||
TrainingStats,
|
||
TrainingType,
|
||
TrainingTypeOption,
|
||
TrainingWorkspaceView,
|
||
LeanTrainingDashboard,
|
||
LeanTrainingDashboardRow,
|
||
LeanTrainingMyTask,
|
||
} from '@/features/chat/training/training.types';
|
||
import {
|
||
SAFETY_STAGE_GUIDE_USAGE_MAP,
|
||
matchesTrainingAgent,
|
||
resolveLearnerCopyText,
|
||
resolveLearnerProgressItems,
|
||
resolveTrainingContentConfig,
|
||
resolveSafetyTrainingVideoGuide,
|
||
type TrainingGuideLike,
|
||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||
|
||
type TrainingAgentLike = {
|
||
id?: number | null;
|
||
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;
|
||
feature_permissions?: {
|
||
training_hr_manage?: boolean;
|
||
} | null;
|
||
} | null | undefined;
|
||
|
||
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
|
||
|
||
export interface UseTrainingWorkspaceOptions {
|
||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||
currentUser: ComputedRef<TrainingUserLike>;
|
||
currentGuides: ComputedRef<TrainingGuideLike[]>;
|
||
}
|
||
|
||
const DEFAULT_PASS_SCORE = 90;
|
||
const DEFAULT_TRAINING_VERSION = 'v1.0';
|
||
|
||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||
|
||
/**
|
||
* 按百分制计算当前答题得分。
|
||
* AI 触发时机:当题库题量改为后台可配置后,不能再假定“每题固定 5 分”,因此每次答题都要按当前题量重新折算分数。
|
||
*/
|
||
const calculateTrainingScore = (correctAnswerCount: number, totalQuestionCount: number) => {
|
||
if (totalQuestionCount <= 0) return 0;
|
||
return Math.round((correctAnswerCount / totalQuestionCount) * 100);
|
||
};
|
||
|
||
/**
|
||
* 规范填空题文本以便与题库标准答案进行即时比对。
|
||
* 用途:忽略作答中的空格和大小写,避免 PDF 文本换行或录入格式导致本应正确的填空题被误判。
|
||
*/
|
||
const normalizeTextAnswer = (value: string) => value
|
||
.normalize('NFKC')
|
||
.replace(/[\s\u3000、,,;;。..!!??::()()【】\[\]{}"'“”‘’\-—_]+/g, '')
|
||
.toLocaleLowerCase();
|
||
|
||
export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||
const { currentAgent, currentUser, currentGuides } = options;
|
||
const { t, tm } = useI18n();
|
||
const msg = useMessage();
|
||
|
||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||
const currentTrainingAgentId = computed<number | null>(() => {
|
||
const parsed = Number(currentAgent.value?.id);
|
||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||
});
|
||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||
const canViewLeanDashboard = computed(() => isAdminViewer.value);
|
||
const canManageTrainingWorkspace = computed(() => isAdminViewer.value);
|
||
/** 学员端精益周任务列表(后端按发布周期倒序,最新在前),并附每期任务状态与完成信息。 */
|
||
const leanMyTasks = ref<LeanTrainingMyTask[]>([]);
|
||
const leanDashboard = ref<LeanTrainingDashboard>({ task: null, completed: [], incomplete: [], periods: [] });
|
||
/** 管理端内容页签:all=全部培训(现有统计/筛选/主表);lean=精益管理(精益看板单任务,按状态列区分三态)。 */
|
||
const hrTrainingTab = ref<'all' | 'lean'>('all');
|
||
/** 管理端精益看板当前选中的期次任务 ID;为空表示最新一期,切换后重新拉取对应期看板。 */
|
||
const leanDashboardTaskId = ref<number | null>(null);
|
||
const leanReminderLoading = ref<Record<number, boolean>>({});
|
||
/** 按任务 ID 分组的感悟草稿,支持时间树上多期任务并行编辑。 */
|
||
const leanSummaryByTask = ref<Record<number, string>>({});
|
||
/** 按任务 ID 分组的观看记录(资源 ID -> 观看时间),提交时随感悟一并交由服务端校验。 */
|
||
const leanWatchedByTask = ref<Record<number, Record<string, string>>>({});
|
||
const defaultActiveView = computed<TrainingWorkspaceView>(() => (canManageTrainingWorkspace.value ? 'admin' : 'learner'));
|
||
const activeView = ref<TrainingWorkspaceView>('learner');
|
||
const learnerTab = ref<TrainingType>('onboarding');
|
||
const trainingTypes = ref<TrainingTypeOption[]>([
|
||
{ code: 'onboarding', name: t('chat.training.safety.tabs.onboarding') },
|
||
{ code: 'safety', name: t('chat.training.safety.tabs.safety') },
|
||
]);
|
||
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION);
|
||
const examMode = ref<TrainingExamMode>('unified');
|
||
const safetyStage = ref<SafetyStage>('company');
|
||
const safetyViewStage = ref<SafetyStage>('company');
|
||
const safetyProgress = ref<SafetyProgressState>({
|
||
company: 'active',
|
||
department: 'pending',
|
||
team: 'pending',
|
||
});
|
||
|
||
const stage = ref<TrainingStage>('video');
|
||
const currentQuestionIndex = ref(0);
|
||
const score = ref(0);
|
||
const attemptCount = ref(0);
|
||
const selectedOptionId = ref('');
|
||
const answerText = ref('');
|
||
const answerLocked = ref(false);
|
||
const currentFeedbackCorrect = ref(false);
|
||
const latestExamFeedback = ref<TrainingExamTransitionFeedback | null>(null);
|
||
const latestSettledResult = ref<{
|
||
score: number;
|
||
correctCount: number;
|
||
wrongCount: number;
|
||
isPassed: boolean;
|
||
} | null>(null);
|
||
const answerRecords = ref<TrainingAnswerRecord[]>([]);
|
||
const completionDate = ref<string | null>(null);
|
||
const currentJoinDate = ref<string | null>(null);
|
||
const isHydrated = ref(false);
|
||
const hasWarnedPersistFailure = ref(false);
|
||
const hasWarnedLoadFailure = ref(false);
|
||
const publishedConfig = ref<TrainingPublishedConfig | null>(null);
|
||
const trainingConfigLoading = ref(false);
|
||
|
||
const hrKeyword = ref('');
|
||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||
const hrDepartmentFilter = ref('all');
|
||
const hrTypeFilter = 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,
|
||
});
|
||
/** 精益看板合并行:已完成+未完成名单合为单表遍历,状态列区分已完成/已延期/进行中三态。 */
|
||
const leanRows = computed<LeanTrainingDashboardRow[]>(() => [...leanDashboard.value.completed, ...leanDashboard.value.incomplete]);
|
||
/**
|
||
* 精益管理页签统计:按看板行三态(completed/in_progress/overdue)实际计数,供统计卡片随页签切换数据源。
|
||
* total=参训人数(已完成+未完成名单行数);passed=已完成;failed=已延期;inProgress=进行中;passRate=完成率。
|
||
*/
|
||
const leanStats = computed<TrainingStats>(() => {
|
||
// [STEP 1] 合并已完成/未完成两组行后按后端归一的三态计数,避免只扫 incomplete 组漏算已延期。
|
||
const rows = [...leanDashboard.value.completed, ...leanDashboard.value.incomplete];
|
||
const total = rows.length;
|
||
const completedCount = rows.filter((row) => row.status === 'completed').length;
|
||
const overdueCount = rows.filter((row) => row.status === 'overdue').length;
|
||
const inProgressCount = rows.filter((row) => row.status === 'in_progress').length;
|
||
return {
|
||
total,
|
||
passed: completedCount,
|
||
failed: overdueCount,
|
||
inProgress: inProgressCount,
|
||
passRate: total > 0 ? Math.round((completedCount / total) * 100) : 0,
|
||
averageScore: 0,
|
||
};
|
||
});
|
||
let persistQueue: Promise<void> = Promise.resolve();
|
||
|
||
watch(isTrainingAgent, (enabled) => {
|
||
if (!enabled) {
|
||
activeView.value = 'learner';
|
||
isHydrated.value = false;
|
||
}
|
||
});
|
||
|
||
watch(
|
||
[isTrainingAgent, canManageTrainingWorkspace],
|
||
([enabled]) => {
|
||
if (!enabled) return;
|
||
activeView.value = defaultActiveView.value;
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
const defaultSummaryPoints = computed(() => {
|
||
const raw = tm('chat.training.summaryPoints');
|
||
return Array.isArray(raw) ? raw.map((item) => String(item)) : [];
|
||
});
|
||
|
||
const defaultSummaryChecklist = 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 mapLocaleQuestionBank = (questionSource: Array<Record<string, unknown>>): TrainingQuestion[] => questionSource.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 || ''),
|
||
scoreRatio: Number(item.score_ratio || item.scoreRatio || 1),
|
||
explanation: String(item.explanation || ''),
|
||
options,
|
||
};
|
||
});
|
||
|
||
const defaultQuestionBank = computed<TrainingQuestion[]>(() => mapLocaleQuestionBank(rawQuestionBank.value));
|
||
|
||
const trainingContent = computed<TrainingContentConfig>(() => resolveTrainingContentConfig(
|
||
currentAgent.value,
|
||
{
|
||
passScore: DEFAULT_PASS_SCORE,
|
||
summaryPoints: defaultSummaryPoints.value,
|
||
summaryChecklist: defaultSummaryChecklist.value,
|
||
questionBank: defaultQuestionBank.value,
|
||
},
|
||
booleanOptions.value,
|
||
publishedConfig.value,
|
||
));
|
||
|
||
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
|
||
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
|
||
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
|
||
const passScore = computed(() => trainingContent.value.passScore);
|
||
const hasPublishedTrainingConfig = computed(() => publishedConfig.value !== null);
|
||
const activeSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
|
||
['company', 'department', 'team'].includes(safetyStage.value)
|
||
? safetyStage.value as SafetyLearningStage
|
||
: null
|
||
));
|
||
const visibleSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
|
||
['company', 'department', 'team'].includes(safetyViewStage.value)
|
||
? safetyViewStage.value as SafetyLearningStage
|
||
: null
|
||
));
|
||
const resolveSafetyStageMaterials = (targetStage: SafetyLearningStage | null) => [...(publishedConfig.value?.resources || [])]
|
||
.filter((resource) => resource.resourceType !== 'inline_questions')
|
||
.filter((resource) => !targetStage || resource.trainingLevel === targetStage)
|
||
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0));
|
||
/**
|
||
* 按当前安全培训阶段筛选已发布资料。
|
||
* AI 触发时机:员工进入公司级、部门级或班组级页面时,只展示后台绑定到当前级别的资料;入职培训仍展示全部非题库资料。
|
||
*/
|
||
const publishedTrainingMaterials = computed(() => [...(publishedConfig.value?.resources || [])]
|
||
.filter((resource) => resource.resourceType !== 'inline_questions')
|
||
.filter((resource) => learnerTab.value !== 'safety' || resource.trainingLevel === visibleSafetyLearningStage.value)
|
||
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0)));
|
||
const publishedSafetySummary = computed(() => {
|
||
const summaries = publishedConfig.value?.settings?.summaryByStage;
|
||
if (!summaries || typeof summaries !== 'object') return [];
|
||
const value = (summaries as Record<string, unknown>)[safetyViewStage.value];
|
||
return Array.isArray(value) ? value.map((item) => String(item)) : [];
|
||
});
|
||
const learnerProgressItems = computed(() => resolveLearnerProgressItems(publishedConfig.value));
|
||
const learnerProgressHintText = computed(() => resolveLearnerCopyText(publishedConfig.value, 'progress_hint_text'));
|
||
const learnerStepIntroText = computed(() => resolveLearnerCopyText(publishedConfig.value, 'step_intro_text'));
|
||
|
||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||
const currentQuestionNumber = computed(() => {
|
||
if (totalQuestionCount.value <= 0) return 0;
|
||
return Math.min(currentQuestionIndex.value + 1, totalQuestionCount.value);
|
||
});
|
||
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 >= passScore.value);
|
||
const examReadyToSubmit = computed(() => (
|
||
stage.value === 'exam'
|
||
&& totalQuestionCount.value > 0
|
||
&& answeredCount.value >= totalQuestionCount.value
|
||
));
|
||
const canEnterResultStage = computed(() => stage.value === 'result');
|
||
const safetyProgressPercent = computed(() => {
|
||
if (safetyStage.value === 'exam') return 90;
|
||
if (safetyStage.value === 'result') return 100;
|
||
|
||
let completedCount = 0;
|
||
if (isStageCompleted('company')) completedCount++;
|
||
if (isStageCompleted('department')) completedCount++;
|
||
if (isStageCompleted('team')) completedCount++;
|
||
|
||
return Math.round((completedCount / 3) * 75) || 10; // Start at 10% or just based on completed
|
||
});
|
||
const isStageCompleted = (stageKey: SafetyLearningStage) => {
|
||
const materials = resolveSafetyStageMaterials(stageKey);
|
||
if (!materials.length) return true;
|
||
return materials.every(m => {
|
||
if (m.id == null) return true;
|
||
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
|
||
return progress?.completed;
|
||
});
|
||
};
|
||
|
||
/**
|
||
* 校验三级安全培训资料是否已全部完成。
|
||
* 用途:在员工端进入或提交安全考试前提供即时拦截;服务端仍会使用同一资源完成事实做最终校验。
|
||
*/
|
||
const isSafetyLearningComplete = () => (
|
||
isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team')
|
||
);
|
||
|
||
const safetyStepItems = computed(() => {
|
||
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
|
||
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
|
||
{ id: 'department', labelKey: 'chat.training.safety.steps.department' },
|
||
{ id: 'team', labelKey: 'chat.training.safety.steps.team' },
|
||
{ id: 'exam', labelKey: 'chat.training.safety.steps.exam' },
|
||
];
|
||
return base.map((item) => {
|
||
let status: 'completed' | 'active' | 'pending' | 'locked' = 'pending';
|
||
if (item.id === 'company' || item.id === 'department' || item.id === 'team') {
|
||
const completed = isStageCompleted(item.id);
|
||
if (safetyViewStage.value === item.id) {
|
||
status = 'active';
|
||
} else if (completed) {
|
||
status = 'completed';
|
||
} else {
|
||
status = 'pending';
|
||
}
|
||
} else if (item.id === 'exam') {
|
||
const allCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
|
||
if (['exam', 'result'].includes(safetyStage.value)) {
|
||
status = safetyStage.value === 'exam' ? 'active' : 'completed';
|
||
} else {
|
||
status = allCompleted ? 'pending' : 'locked';
|
||
}
|
||
}
|
||
return {
|
||
id: item.id,
|
||
label: t(item.labelKey),
|
||
status,
|
||
};
|
||
});
|
||
});
|
||
|
||
const learnerProgressPercent = computed(() => {
|
||
if (learnerTab.value === 'safety') {
|
||
return safetyProgressPercent.value;
|
||
}
|
||
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 触发时机:Tabs、HR 筛选、记录和报告展示培训类型时调用,禁止直接将类型 code 暴露给用户。
|
||
*/
|
||
const resolveTrainingTypeName = (code?: string | null) => {
|
||
const normalizedCode = String(code || '').trim();
|
||
return trainingTypes.value.find((item) => item.code === normalizedCode)?.name
|
||
|| (normalizedCode === 'onboarding' ? t('chat.training.hr.filters.typeOnboarding') : '')
|
||
|| (normalizedCode === 'safety' ? t('chat.training.hr.filters.typeSafety') : '')
|
||
|| normalizedCode
|
||
|| '--';
|
||
};
|
||
|
||
/**
|
||
* 读取员工可见的已发布培训类型,作为动态 Tabs 与 HR 类型筛选的统一数据源。
|
||
* AI 触发时机:进入培训 Agent 或登录状态变更后调用;无已发布配置时保留内置类型以兼容历史数据。
|
||
*/
|
||
const loadTrainingTypes = async () => {
|
||
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
|
||
try {
|
||
const items = await getMyTrainingTypes();
|
||
if (!items.length) return;
|
||
trainingTypes.value = items;
|
||
if (!items.some((item) => item.code === learnerTab.value)) {
|
||
learnerTab.value = items[0]?.code || learnerTab.value;
|
||
}
|
||
} catch {
|
||
// 无法读取目录时保留内置兼容项,后续仍可按 code 请求配置。
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 重置考试状态,为首次开考或再次补考共用。
|
||
* AI 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
|
||
*/
|
||
const resetExamState = () => {
|
||
currentQuestionIndex.value = 0;
|
||
score.value = 0;
|
||
selectedOptionId.value = '';
|
||
answerText.value = '';
|
||
answerLocked.value = false;
|
||
currentFeedbackCorrect.value = false;
|
||
latestExamFeedback.value = null;
|
||
answerRecords.value = [];
|
||
completionDate.value = null;
|
||
};
|
||
|
||
/**
|
||
* 读取题目选项展示文案,避免在聊天反馈里直接暴露内部 option id。
|
||
* AI 触发时机:当培训聊天流需要把上一题答题结果翻译成员工可读文案时使用。
|
||
*/
|
||
const getQuestionOptionLabel = (question: TrainingQuestion | null, optionId: string) => {
|
||
if (!question) return optionId;
|
||
return question.options?.find((item) => item.id === optionId)?.label || optionId;
|
||
};
|
||
|
||
/**
|
||
* 生成“上一题即时反馈”摘要,供聊天题卡在自动推进到下一题后继续展示。
|
||
* AI 触发时机:当员工刚答完一道题、或刷新页面后要恢复“反馈 + 下一题”联动体验时使用。
|
||
*/
|
||
const buildExamFeedback = (
|
||
question: TrainingQuestion | null,
|
||
answerRecord: TrainingAnswerRecord | null | undefined,
|
||
scoreAfterAnswer: number,
|
||
): TrainingExamTransitionFeedback | null => {
|
||
if (!question || !answerRecord) return null;
|
||
return {
|
||
questionId: question.id,
|
||
questionPrompt: question.prompt,
|
||
selectedAnswerLabel: getQuestionOptionLabel(question, answerRecord.selectedOptionId),
|
||
correctAnswerLabel: getQuestionOptionLabel(question, question.answer),
|
||
explanation: question.explanation,
|
||
correct: Boolean(answerRecord.correct),
|
||
scoreAfterAnswer,
|
||
};
|
||
};
|
||
|
||
const getQuestionTypeLabel = (question: TrainingQuestion | null) => (
|
||
question?.type === 'boolean'
|
||
? t('chat.training.chatPrompts.assistantQuestionBooleanType')
|
||
: t('chat.training.chatPrompts.assistantQuestionSingleType')
|
||
);
|
||
|
||
const buildExamQuestionMessage = (question: TrainingQuestion | null, questionIndex: number) => {
|
||
if (!question) return '';
|
||
const optionLines = (question.options || []).map((option) => option.label).join('\n');
|
||
return [
|
||
`📝 **${t('chat.training.exam.questionCounter', { current: questionIndex + 1, total: totalQuestionCount.value })}(${getQuestionTypeLabel(question)})**:${question.prompt}`,
|
||
optionLines,
|
||
t('chat.training.chatPrompts.assistantQuestionReplyHint'),
|
||
].filter(Boolean).join('\n');
|
||
};
|
||
|
||
const buildSummaryAssistantMessage = () => {
|
||
const summaryLines = summaryPoints.value.map((point, index) => `${index + 1}. ${point}`).join('\n');
|
||
return [
|
||
t('chat.training.chatPrompts.assistantSummaryIntro'),
|
||
summaryLines,
|
||
'',
|
||
t('chat.training.chatPrompts.assistantSummaryReady'),
|
||
].join('\n');
|
||
};
|
||
|
||
/**
|
||
* 基于当前答题记录重算成绩,保证“修改答案”后分数与结果页口径一致。
|
||
* AI 触发时机:当培训考试支持点击题号返回修改答案时,不能再用“上一题答对就直接 +1”的增量算法。
|
||
*/
|
||
const recalculateScoreFromAnswers = (records: TrainingAnswerRecord[]) => calculateTrainingScore(
|
||
records.filter((item) => item.correct).length,
|
||
totalQuestionCount.value,
|
||
);
|
||
|
||
/**
|
||
* 覆盖或新增当前题的作答记录,避免同一道题在进度里出现重复答案。
|
||
* AI 触发时机:当员工返回已答题修改答案时,必须覆盖旧答案而不是重复追加,否则分数和已答题数都会失真。
|
||
*/
|
||
const upsertAnswerRecord = (nextRecord: TrainingAnswerRecord) => {
|
||
const existingIndex = answerRecords.value.findIndex((item) => item.questionId === nextRecord.questionId);
|
||
if (existingIndex >= 0) {
|
||
answerRecords.value.splice(existingIndex, 1, nextRecord);
|
||
return true;
|
||
}
|
||
answerRecords.value.push(nextRecord);
|
||
return false;
|
||
};
|
||
|
||
const syncAnswerStateForCurrentQuestion = () => {
|
||
const questionId = currentQuestion.value?.id;
|
||
const currentAnswer = questionId
|
||
? answerRecords.value.find((item) => item.questionId === questionId)
|
||
: null;
|
||
selectedOptionId.value = currentAnswer?.selectedOptionId || '';
|
||
answerText.value = currentAnswer?.answerText || '';
|
||
answerLocked.value = Boolean(currentAnswer);
|
||
currentFeedbackCorrect.value = currentQuestion.value?.type === 'fill' && currentQuestion.value.answer && currentAnswer?.answerText
|
||
? normalizeTextAnswer(currentAnswer.answerText) === normalizeTextAnswer(currentQuestion.value.answer)
|
||
: Boolean(currentAnswer?.correct);
|
||
};
|
||
|
||
/**
|
||
* 切换考试题目时,同步左侧题干、已答状态和反馈展示。
|
||
* AI 触发时机:当员工点击右侧题号导航或后端恢复考试进度时,必须保证“当前题序号、选中项、答题对错反馈”完全一致。
|
||
*/
|
||
const syncExamQuestionIndex = (nextIndex: number) => {
|
||
if (totalQuestionCount.value <= 0) {
|
||
currentQuestionIndex.value = 0;
|
||
syncAnswerStateForCurrentQuestion();
|
||
return;
|
||
}
|
||
const normalizedIndex = Math.min(Math.max(nextIndex, 0), totalQuestionCount.value - 1);
|
||
currentQuestionIndex.value = normalizedIndex;
|
||
syncAnswerStateForCurrentQuestion();
|
||
};
|
||
|
||
/**
|
||
* 按安全培训目标阶段重置三级学习进度。
|
||
* AI 触发时机:当员工完成上一级学习、切换安全培训阶段,或后端恢复安全培训初始态时,需要一次性得到完整的三级状态快照。
|
||
*/
|
||
const resetSafetyProgress = (nextStage: SafetyStage = 'company') => {
|
||
const resourceProgressSnapshot = safetyProgress.value.resource_progress
|
||
? { ...safetyProgress.value.resource_progress }
|
||
: undefined;
|
||
safetyStage.value = nextStage;
|
||
safetyViewStage.value = nextStage;
|
||
if (nextStage === 'company') {
|
||
safetyProgress.value = { company: 'active', department: 'pending', team: 'pending', resource_progress: resourceProgressSnapshot };
|
||
return;
|
||
}
|
||
if (nextStage === 'department') {
|
||
safetyProgress.value = { company: 'completed', department: 'active', team: 'pending', resource_progress: resourceProgressSnapshot };
|
||
return;
|
||
}
|
||
if (nextStage === 'team') {
|
||
safetyProgress.value = { company: 'completed', department: 'completed', team: 'active', resource_progress: resourceProgressSnapshot };
|
||
return;
|
||
}
|
||
safetyProgress.value = { company: 'completed', department: 'completed', team: 'completed', resource_progress: resourceProgressSnapshot };
|
||
};
|
||
|
||
/**
|
||
* 进入安全培训考试阶段并初始化本轮考试状态。
|
||
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
|
||
*/
|
||
const enterSafetyExam = () => {
|
||
if (!isSafetyLearningComplete()) {
|
||
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
|
||
return;
|
||
}
|
||
if (totalQuestionCount.value <= 0) {
|
||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||
return;
|
||
}
|
||
safetyStage.value = 'exam';
|
||
safetyViewStage.value = 'exam';
|
||
stage.value = 'exam';
|
||
attemptCount.value += 1;
|
||
resetExamState();
|
||
};
|
||
|
||
/**
|
||
* 把后端培训记录回填到当前工作区状态。
|
||
* AI 触发时机:页面刷新、重新进入聊天页或切换培训类型后,需要把服务端快照完整恢复到本地状态机。
|
||
*/
|
||
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
|
||
if (!record) {
|
||
trainingVersion.value = DEFAULT_TRAINING_VERSION;
|
||
examMode.value = 'unified';
|
||
resetSafetyProgress('company');
|
||
stage.value = 'video';
|
||
resetExamState();
|
||
currentJoinDate.value = null;
|
||
latestSettledResult.value = null;
|
||
return;
|
||
}
|
||
trainingVersion.value = record.trainingVersion || publishedConfig.value?.version || DEFAULT_TRAINING_VERSION;
|
||
examMode.value = record.examMode || 'unified';
|
||
if (learnerTab.value === 'safety') {
|
||
safetyStage.value = record.safetyStage || 'company';
|
||
// Ensure resource_progress is preserved when merging from backend
|
||
safetyProgress.value = {
|
||
...record.safetyProgress,
|
||
resource_progress: record.safetyProgress?.resource_progress || safetyProgress.value.resource_progress || {}
|
||
};
|
||
|
||
// Sync legacy fields with actual resource completion
|
||
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
|
||
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
|
||
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
|
||
|
||
if (safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
|
||
if (!isStageCompleted('company')) {
|
||
safetyViewStage.value = 'company';
|
||
} else if (!isStageCompleted('department')) {
|
||
safetyViewStage.value = 'department';
|
||
} else if (!isStageCompleted('team')) {
|
||
safetyViewStage.value = 'team';
|
||
} else {
|
||
safetyViewStage.value = 'company';
|
||
}
|
||
} else {
|
||
safetyViewStage.value = record.safetyStage || 'company';
|
||
}
|
||
}
|
||
stage.value = record.stage;
|
||
syncExamQuestionIndex(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;
|
||
latestExamFeedback.value = null;
|
||
if (record.stage === 'result') {
|
||
latestSettledResult.value = {
|
||
score: Number(record.score || 0),
|
||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||
isPassed: Boolean(record.passed || Number(record.score || 0) >= passScore.value),
|
||
};
|
||
}
|
||
if (record.stage === 'exam' && record.currentQuestionIndex > 0) {
|
||
const previousQuestion = questionBank.value[record.currentQuestionIndex - 1] || null;
|
||
const previousAnswer = previousQuestion
|
||
? answerRecords.value.find((item) => item.questionId === previousQuestion.id)
|
||
: null;
|
||
latestExamFeedback.value = buildExamFeedback(previousQuestion, previousAnswer, Number(record.score || 0));
|
||
}
|
||
syncAnswerStateForCurrentQuestion();
|
||
};
|
||
|
||
/**
|
||
* 组装当前培训工作区的持久化载荷。
|
||
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
|
||
*/
|
||
const buildProgressPayload = () => ({
|
||
agentId: currentTrainingAgentId.value,
|
||
stage: learnerTab.value === 'safety'
|
||
? (safetyStage.value === 'exam' ? 'exam' : safetyStage.value === 'result' ? 'result' : 'summary')
|
||
: stage.value,
|
||
trainingVersion: trainingVersion.value,
|
||
examMode: examMode.value,
|
||
safetyStage: learnerTab.value === 'safety' ? safetyStage.value : null,
|
||
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
|
||
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(), learnerTab.value);
|
||
hasWarnedPersistFailure.value = false;
|
||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||
completionDate.value = saved.completionDate;
|
||
score.value = Number(saved.score || 0);
|
||
answerRecords.value = saved.answerDetails;
|
||
if (isAdminViewer.value) {
|
||
void loadAdminRecords();
|
||
}
|
||
} catch (error) {
|
||
if (!hasWarnedPersistFailure.value) {
|
||
hasWarnedPersistFailure.value = true;
|
||
const message = error instanceof BusinessError
|
||
? error.message
|
||
: t('errors.generic');
|
||
msg.error({
|
||
title: t('chat.training.errors.persistTitle'),
|
||
message: `${t('chat.training.errors.persistBody')}:${message}`,
|
||
});
|
||
}
|
||
}
|
||
});
|
||
await persistQueue;
|
||
};
|
||
|
||
const loadTrainingProgress = async () => {
|
||
if (!isTrainingAgent.value) return;
|
||
if (!hasAuthenticatedUser.value) {
|
||
hasWarnedLoadFailure.value = false;
|
||
applyProgressRecord(null);
|
||
isHydrated.value = true;
|
||
return;
|
||
}
|
||
try {
|
||
const record = await getMyTrainingProgress(learnerTab.value);
|
||
hasWarnedLoadFailure.value = false;
|
||
applyProgressRecord(record);
|
||
} catch (error) {
|
||
// 退出登录或登录态失效时,培训页可能尚未卸载;这里静默清空状态,避免把正常 401 提示成“读取失败”。
|
||
if (error instanceof BusinessError && error.status === 401) {
|
||
hasWarnedLoadFailure.value = false;
|
||
applyProgressRecord(null);
|
||
return;
|
||
}
|
||
if (!hasWarnedLoadFailure.value) {
|
||
hasWarnedLoadFailure.value = true;
|
||
const message = error instanceof BusinessError
|
||
? error.message
|
||
: t('errors.generic');
|
||
msg.warning({
|
||
title: t('chat.training.errors.loadTitle'),
|
||
message: `${t('chat.training.errors.loadBody')}:${message}`,
|
||
});
|
||
}
|
||
applyProgressRecord(null);
|
||
} finally {
|
||
isHydrated.value = true;
|
||
}
|
||
};
|
||
|
||
const loadTrainingConfig = async () => {
|
||
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) {
|
||
publishedConfig.value = null;
|
||
trainingConfigLoading.value = false;
|
||
return;
|
||
}
|
||
trainingConfigLoading.value = true;
|
||
try {
|
||
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
|
||
} catch (error) {
|
||
if (!(error instanceof BusinessError && error.status === 401)) {
|
||
publishedConfig.value = null;
|
||
}
|
||
} finally {
|
||
trainingConfigLoading.value = false;
|
||
}
|
||
};
|
||
|
||
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,
|
||
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.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,
|
||
};
|
||
}
|
||
};
|
||
|
||
/** 拉取管理端精益看板(按 leanDashboardTaskId 指定期次,空则最新一期),失败时清空兜底。 */
|
||
const loadLeanDashboard = async () => {
|
||
if (!canViewLeanDashboard.value) return;
|
||
try {
|
||
leanDashboard.value = await getLeanTrainingDashboard(leanDashboardTaskId.value ?? undefined);
|
||
} catch {
|
||
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
|
||
}
|
||
};
|
||
|
||
/** 切换精益看板期次:记录任务 ID 后仅重拉看板与精益统计,不动学员任务列表。 */
|
||
const selectLeanDashboardPeriod = async (taskId: number) => {
|
||
if (leanDashboardTaskId.value === taskId) return;
|
||
leanDashboardTaskId.value = taskId;
|
||
await loadLeanDashboard();
|
||
};
|
||
|
||
/** 读取学员端全部已发布精益周任务(含状态与播放地址),并以服务端完成记录回填各任务的感悟/观看草稿。 */
|
||
const loadLeanTraining = async () => {
|
||
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) return;
|
||
try {
|
||
leanMyTasks.value = await getMyLeanTrainingTasks();
|
||
// [STEP 1] 回填草稿:已完成任务还原当时提交的感悟与观看时间;进行中/已延期任务保留已有观看记录,避免刷新后丢失。
|
||
const summaries: Record<number, string> = {};
|
||
const watched: Record<number, Record<string, string>> = {};
|
||
leanMyTasks.value.forEach((task) => {
|
||
summaries[task.id] = task.completion?.summaryText || '';
|
||
watched[task.id] = { ...(task.completion?.watchedAt || {}) };
|
||
});
|
||
leanSummaryByTask.value = summaries;
|
||
leanWatchedByTask.value = watched;
|
||
await loadLeanDashboard();
|
||
} catch {
|
||
leanMyTasks.value = [];
|
||
leanDashboard.value = { task: null, completed: [], incomplete: [], periods: [] };
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 记录某期任务的指定视频已完成观看:本地即时生效,并异步持久化到服务端(刷新后仍保留)。
|
||
* AI 触发时机:学员在精益管理时间树上点击任务视频并完整播放到结尾时调用;已有观看记录的资源保留首次时间不覆盖。
|
||
*/
|
||
const markLeanVideoWatched = (taskId: number, resourceId: number) => {
|
||
const taskWatched = leanWatchedByTask.value[taskId] || {};
|
||
if (taskWatched[String(resourceId)]) return;
|
||
leanWatchedByTask.value = { ...leanWatchedByTask.value, [taskId]: { ...taskWatched, [String(resourceId)]: new Date().toISOString() } };
|
||
// 持久化失败不阻塞本地状态;下次刷新列表会以服务端记录为准,未持久化的视频需重新完整观看
|
||
void markMyLeanVideoWatched(taskId, resourceId).catch(() => {});
|
||
};
|
||
|
||
/**
|
||
* 提交指定周任务的学习感悟;服务端校验该任务已推送视频全部完成且达到最少字数,成功后刷新任务列表与看板。
|
||
*/
|
||
const submitLeanTrainingCompletion = async (taskId: number) => {
|
||
await saveMyLeanTrainingCompletion({ weeklyTaskId: taskId, watchedAt: leanWatchedByTask.value[taskId] || {}, summaryText: leanSummaryByTask.value[taskId] || '' });
|
||
await loadLeanTraining();
|
||
};
|
||
|
||
/**
|
||
* HR 对看板中未完成成员发起定向提醒,并按服务端实发统计如实提示。
|
||
* AI 触发时机:HR 在精益培训完成名单点击行内【提醒】按钮时调用。
|
||
* 核心逻辑:后端 created 计数包含"企微发送失败"的提醒(仅代表已尝试),
|
||
* 成功提示必须以 sent(企微受理成功)为准,failed>0 时明确告知失败,避免误报已送达。
|
||
*/
|
||
const remindLeanTrainingMember = async (userId: number) => {
|
||
if (!leanDashboard.value.task || leanReminderLoading.value[userId]) return;
|
||
leanReminderLoading.value[userId] = true;
|
||
try {
|
||
const result = await sendLeanTrainingReminders(leanDashboard.value.task.id, [userId]);
|
||
if (result.sent > 0 && result.failed > 0) {
|
||
msg.warning(t('chat.training.lean.reminder.partial', { sent: result.sent, failed: result.failed }));
|
||
} else if (result.sent > 0) {
|
||
msg.success(t('chat.training.lean.reminder.success', { count: result.sent }));
|
||
} else if (result.failed > 0) {
|
||
msg.error(t('chat.training.lean.reminder.sendFailed', { count: result.failed }));
|
||
} else {
|
||
msg.warning(t('chat.training.lean.reminder.notSent'));
|
||
}
|
||
await loadLeanTraining();
|
||
} catch (error) {
|
||
msg.error(error instanceof BusinessError ? error.message : t('chat.training.lean.reminder.failed'));
|
||
} finally {
|
||
leanReminderLoading.value[userId] = false;
|
||
}
|
||
};
|
||
|
||
watch(
|
||
[
|
||
currentAgent,
|
||
hasAuthenticatedUser,
|
||
() => String(currentUser.value?.username || '').trim(),
|
||
() => String(currentUser.value?.role || '').trim(),
|
||
learnerTab,
|
||
],
|
||
([agent, loggedIn]) => {
|
||
if (!matchesTrainingAgent(agent)) {
|
||
records.value = [];
|
||
departmentOptions.value = [];
|
||
stats.value = {
|
||
total: 0,
|
||
passed: 0,
|
||
failed: 0,
|
||
inProgress: 0,
|
||
passRate: 0,
|
||
averageScore: 0,
|
||
};
|
||
return;
|
||
}
|
||
if (!loggedIn) {
|
||
hasWarnedLoadFailure.value = false;
|
||
applyProgressRecord(null);
|
||
isHydrated.value = true;
|
||
return;
|
||
}
|
||
isHydrated.value = false;
|
||
void loadTrainingTypes();
|
||
void loadTrainingConfig();
|
||
void loadTrainingProgress();
|
||
void loadLeanTraining();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
watch(
|
||
[
|
||
isTrainingAgent,
|
||
isAdminViewer,
|
||
hrKeyword,
|
||
hrStatusFilter,
|
||
hrDepartmentFilter,
|
||
hrTypeFilter,
|
||
() => String(currentUser.value?.username || '').trim(),
|
||
() => String(currentUser.value?.role || '').trim(),
|
||
],
|
||
([enabled, canView]) => {
|
||
if (!enabled || !canView) return;
|
||
void loadAdminRecords();
|
||
},
|
||
{ immediate: true },
|
||
);
|
||
|
||
const markVideoCompleted = () => {
|
||
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
|
||
if (learnerTab.value === 'safety') {
|
||
checkAndAdvanceStage();
|
||
return;
|
||
}
|
||
stage.value = 'summary';
|
||
void persistProgress();
|
||
};
|
||
|
||
const startExam = () => {
|
||
if (!hasPublishedTrainingConfig.value) return;
|
||
if (learnerTab.value === 'safety') {
|
||
enterSafetyExam();
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
if (totalQuestionCount.value <= 0) {
|
||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||
return;
|
||
}
|
||
stage.value = 'exam';
|
||
attemptCount.value += 1;
|
||
resetExamState();
|
||
void persistProgress();
|
||
};
|
||
|
||
/**
|
||
* 记录当前题答案;首次作答沿用自动推进,回看题目时则覆盖旧答案并实时重算分数。
|
||
* AI 触发时机:当员工在逐题考试阶段点击右侧题号返回某题时,需要允许直接改答且不破坏“提交答卷后才结算”的流程。
|
||
*/
|
||
const selectAnswer = (optionId: string) => {
|
||
if (!currentQuestion.value || currentQuestion.value.type === 'fill' || currentQuestion.value.type === 'essay') return;
|
||
const answeredQuestion = currentQuestion.value;
|
||
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
|
||
selectedOptionId.value = optionId;
|
||
answerLocked.value = true;
|
||
const isCorrect = optionId === answeredQuestion.answer;
|
||
currentFeedbackCorrect.value = isCorrect;
|
||
const answerRecord: TrainingAnswerRecord = {
|
||
questionId: answeredQuestion.id,
|
||
selectedOptionId: optionId,
|
||
correct: isCorrect,
|
||
};
|
||
upsertAnswerRecord(answerRecord);
|
||
const nextScore = recalculateScoreFromAnswers(answerRecords.value);
|
||
score.value = nextScore;
|
||
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
|
||
|
||
// [STEP 1] 已答题被回看并改答时,停留在当前题,方便继续检查或跳到其他题。
|
||
if (hadExistingAnswer) {
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
|
||
// [STEP 2] 最后一题首次答完后先停留在考试阶段,必须点击“提交答卷”才能进入结算结果。
|
||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
|
||
// [STEP 3] 首次作答且不是最后一题时,自动推进到下一题。
|
||
syncExamQuestionIndex(currentQuestionIndex.value + 1);
|
||
void persistProgress();
|
||
};
|
||
|
||
/**
|
||
* 提交填空或问答题的文本作答。
|
||
* 核心逻辑:文本题由服务端以题库标准答案或无标准答案的字数规则最终判卷;前端仅保存非空文本并推进。
|
||
* @returns 无有效文本时不记录,否则更新当前题作答并保持既有逐题推进行为。
|
||
*/
|
||
const submitTextAnswer = () => {
|
||
if (!currentQuestion.value || !['fill', 'essay'].includes(currentQuestion.value.type)) return;
|
||
const answeredQuestion = currentQuestion.value;
|
||
const text = answerText.value.trim();
|
||
if (!text) return;
|
||
const hadExistingAnswer = answerRecords.value.some((item) => item.questionId === answeredQuestion.id);
|
||
const answerRecord: TrainingAnswerRecord = {
|
||
questionId: answeredQuestion.id,
|
||
selectedOptionId: '',
|
||
answerText: text,
|
||
correct: answeredQuestion.type === 'fill' && answeredQuestion.answer
|
||
? normalizeTextAnswer(text) === normalizeTextAnswer(answeredQuestion.answer)
|
||
: false,
|
||
scoreRatio: 0,
|
||
};
|
||
answerLocked.value = true;
|
||
upsertAnswerRecord(answerRecord);
|
||
const nextScore = recalculateScoreFromAnswers(answerRecords.value);
|
||
score.value = nextScore;
|
||
currentFeedbackCorrect.value = answerRecord.correct;
|
||
latestExamFeedback.value = buildExamFeedback(answeredQuestion, answerRecord, nextScore);
|
||
if (hadExistingAnswer || currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
syncExamQuestionIndex(currentQuestionIndex.value + 1);
|
||
void persistProgress();
|
||
};
|
||
|
||
/**
|
||
* 进入下一题或结束考试。
|
||
* AI 触发时机:当用户答完一题后,前端必须只推进一题并即时结算,保证“一题一答一反馈”的 HR 规则被严格执行。
|
||
*/
|
||
const moveToNextQuestion = () => {
|
||
if (!answerLocked.value) return;
|
||
if (currentQuestionIndex.value >= totalQuestionCount.value - 1) {
|
||
return;
|
||
}
|
||
syncExamQuestionIndex(currentQuestionIndex.value + 1);
|
||
latestExamFeedback.value = null;
|
||
void persistProgress();
|
||
};
|
||
|
||
/**
|
||
* 统一提交整份答卷并进入结算结果。
|
||
* AI 触发时机:当员工已完成全部题目但尚未结算时,必须显式点击“提交答卷”后才允许进入第 4 阶段。
|
||
*/
|
||
const submitExam = () => {
|
||
if (!examReadyToSubmit.value) return;
|
||
if (learnerTab.value === 'safety' && !isSafetyLearningComplete()) {
|
||
msg.warning(t('chat.training.errors.safetyLearningIncomplete'));
|
||
return;
|
||
}
|
||
stage.value = 'result';
|
||
if (learnerTab.value === 'safety') {
|
||
safetyStage.value = 'result';
|
||
safetyViewStage.value = 'result';
|
||
}
|
||
completionDate.value = formatDate(new Date());
|
||
latestSettledResult.value = {
|
||
score: score.value,
|
||
correctCount: answerRecords.value.filter((item) => item.correct).length,
|
||
wrongCount: answerRecords.value.filter((item) => !item.correct).length,
|
||
isPassed: score.value >= passScore.value,
|
||
};
|
||
void persistProgress();
|
||
};
|
||
|
||
const restartExam = () => {
|
||
if (learnerTab.value === 'safety') {
|
||
enterSafetyExam();
|
||
void persistProgress();
|
||
return;
|
||
}
|
||
stage.value = 'video';
|
||
resetExamState();
|
||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||
};
|
||
|
||
/**
|
||
* 按右侧步骤面板切换安全培训阶段。
|
||
* AI 触发时机:当员工点击安全培训流程步骤时,只允许查看当前可达阶段,
|
||
* 但绝不能因为“返回查看已完成阶段”而重置已保存的完成状态或学习记录。
|
||
*/
|
||
const setSafetyStage = (nextStage: SafetyStage) => {
|
||
if (!hasPublishedTrainingConfig.value) return;
|
||
const target = safetyStepItems.value.find((item) => item.id === nextStage);
|
||
if (!target || target.status === 'locked') return;
|
||
|
||
if (nextStage === 'exam' && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
|
||
enterSafetyExam();
|
||
void persistProgress();
|
||
} else {
|
||
safetyViewStage.value = nextStage;
|
||
}
|
||
};
|
||
|
||
const exportRecords = async () => {
|
||
await exportTrainingRecords({
|
||
keyword: hrKeyword.value || undefined,
|
||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||
status: hrStatusFilter.value,
|
||
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.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.typeLabel')}: ${hrTypeFilter.value === 'all' ? t('chat.training.hr.filters.allTypes') : resolveTrainingTypeName(hrTypeFilter.value)}`,
|
||
`${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(() => {
|
||
// 发送给 Agent 的“用户侧”提示语,用于同步当前培训上下文到正式聊天链路。
|
||
if (stage.value === 'video') return t('chat.training.chatPrompts.afterVideo');
|
||
if (stage.value === 'summary') return t('chat.training.chatPrompts.afterSummary');
|
||
if (stage.value === 'result') {
|
||
return isPassed.value
|
||
? t('chat.training.chatPrompts.afterPass', { score: score.value })
|
||
: t('chat.training.chatPrompts.afterFail', { score: score.value });
|
||
}
|
||
return t('chat.training.chatPrompts.examInProgress', {
|
||
index: currentQuestionIndex.value + 1,
|
||
total: totalQuestionCount.value,
|
||
question: currentQuestion.value?.prompt || '',
|
||
});
|
||
});
|
||
|
||
/**
|
||
* 新建培训聊天会话时使用的统一提醒文案。
|
||
* AI 触发时机:当员工进入培训 Agent 的空白新会话,且当前考试尚未通过时,必须像首次进入一样重新提醒培训要求。
|
||
*/
|
||
const newSessionReminderMessage = computed(() => t('chat.training.chatPrompts.assistantVideoIntro', {
|
||
passScore: passScore.value,
|
||
}));
|
||
const shouldShowNewSessionReminder = computed(() => !isPassed.value);
|
||
|
||
const learnerAssistantMessage = computed(() => {
|
||
// 发送到本地聊天框的“助手侧”文案,对齐培训设计文档中的四阶段话术。
|
||
if (stage.value === 'video') {
|
||
return t('chat.training.chatPrompts.assistantVideoIntro', { passScore: passScore.value });
|
||
}
|
||
if (stage.value === 'summary') {
|
||
return buildSummaryAssistantMessage();
|
||
}
|
||
if (stage.value === 'result') {
|
||
return isPassed.value
|
||
? t('chat.training.chatPrompts.assistantResultPass', { score: score.value })
|
||
: t('chat.training.chatPrompts.assistantResultFail', { score: score.value, passScore: passScore.value });
|
||
}
|
||
return buildExamQuestionMessage(currentQuestion.value, currentQuestionIndex.value);
|
||
});
|
||
|
||
const showVideoModal = ref(false);
|
||
const currentViewingMaterialId = ref<number | null>(null);
|
||
const materialStartTime = ref<number>(0);
|
||
|
||
const currentViewingMaterialRequiredDuration = computed(() => {
|
||
if (!currentViewingMaterialId.value) return 0;
|
||
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === String(currentViewingMaterialId.value));
|
||
return resource?.requiredDuration || 0;
|
||
});
|
||
|
||
const startMaterialTimer = (materialId: number) => {
|
||
currentViewingMaterialId.value = materialId;
|
||
materialStartTime.value = Date.now();
|
||
};
|
||
|
||
const stopMaterialTimer = () => {
|
||
if (!currentViewingMaterialId.value || !materialStartTime.value) return;
|
||
const materialId = String(currentViewingMaterialId.value);
|
||
// 累计观看时长(秒)
|
||
const durationSeconds = Math.round((Date.now() - materialStartTime.value) / 1000);
|
||
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === materialId);
|
||
|
||
if (resource) {
|
||
if (!safetyProgress.value.resource_progress) {
|
||
safetyProgress.value.resource_progress = {};
|
||
}
|
||
const existing = safetyProgress.value.resource_progress[materialId] || { duration: 0, completed: false };
|
||
existing.duration += durationSeconds;
|
||
|
||
const reqDurationMinutes = resource.requiredDuration || 0;
|
||
if (existing.duration >= reqDurationMinutes * 60) {
|
||
existing.completed = true;
|
||
}
|
||
safetyProgress.value.resource_progress[materialId] = existing;
|
||
|
||
checkAndAdvanceStage();
|
||
}
|
||
|
||
currentViewingMaterialId.value = null;
|
||
materialStartTime.value = 0;
|
||
};
|
||
|
||
const checkAndAdvanceStage = () => {
|
||
// Update legacy string fields to reflect real status based on resources
|
||
safetyProgress.value.company = isStageCompleted('company') ? 'completed' : 'active';
|
||
safetyProgress.value.department = isStageCompleted('department') ? 'completed' : 'active';
|
||
safetyProgress.value.team = isStageCompleted('team') ? 'completed' : 'active';
|
||
|
||
if (learnerTab.value === 'safety') {
|
||
const allSafetyCompleted = isStageCompleted('company') && isStageCompleted('department') && isStageCompleted('team');
|
||
|
||
if (allSafetyCompleted && safetyStage.value !== 'exam' && safetyStage.value !== 'result') {
|
||
safetyStage.value = 'exam';
|
||
enterSafetyExam();
|
||
}
|
||
void persistProgress();
|
||
} else {
|
||
const activeStageMaterials = publishedTrainingMaterials.value;
|
||
if (!activeStageMaterials.length) return;
|
||
const allCompleted = activeStageMaterials.every(m => {
|
||
if (m.id == null) return true;
|
||
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
|
||
return progress?.completed;
|
||
});
|
||
|
||
if (allCompleted) {
|
||
stage.value = 'summary';
|
||
}
|
||
void persistProgress();
|
||
}
|
||
};
|
||
|
||
const videoUrl = computed(() => {
|
||
if (!publishedConfig.value) return '';
|
||
const visibleGuideStage = visibleSafetyLearningStage.value || activeSafetyLearningStage.value;
|
||
const preferredGuideIds = publishedTrainingMaterials.value
|
||
.filter((resource) => resource.resourceType === 'agent_guide' && resource.agentGuideId != null)
|
||
.map((resource) => Number(resource.agentGuideId));
|
||
const uploadedGuide = learnerTab.value === 'safety'
|
||
? resolveSafetyTrainingVideoGuide(currentGuides.value, visibleGuideStage || 'company', preferredGuideIds)
|
||
: currentGuides.value.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video');
|
||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||
const configuredGuide = publishedTrainingMaterials.value
|
||
.find((resource) => resource.resourceType === 'agent_guide'
|
||
&& resource.resource?.fileType === 'video'
|
||
&& (learnerTab.value !== 'safety'
|
||
|| !visibleGuideStage
|
||
|| !SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|
||
|| resource.resource.guideUsage === SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]));
|
||
return String(configuredGuide?.resource?.fileUrl || '').trim()
|
||
|| uploadedGuideUrl;
|
||
});
|
||
|
||
return {
|
||
isTrainingAgent,
|
||
isAdminViewer,
|
||
canViewLeanDashboard,
|
||
canManageTrainingWorkspace,
|
||
leanDashboard,
|
||
leanReminderLoading,
|
||
leanSummaryByTask,
|
||
leanWatchedByTask,
|
||
leanMyTasks,
|
||
isHydrated,
|
||
trainingConfigLoading,
|
||
hasPublishedTrainingConfig,
|
||
publishedTrainingMaterials,
|
||
publishedSafetySummary,
|
||
learnerProgressItems,
|
||
learnerProgressHintText,
|
||
learnerStepIntroText,
|
||
activeView,
|
||
learnerTab,
|
||
trainingTypes,
|
||
resolveTrainingTypeName,
|
||
trainingVersion,
|
||
examMode,
|
||
safetyStage,
|
||
safetyViewStage,
|
||
safetyProgress,
|
||
safetyProgressPercent,
|
||
safetyStepItems,
|
||
stage,
|
||
currentQuestionIndex,
|
||
currentQuestionNumber,
|
||
currentQuestion,
|
||
questionBank,
|
||
totalQuestionCount,
|
||
passScore,
|
||
answeredCount,
|
||
score,
|
||
attemptCount,
|
||
selectedOptionId,
|
||
answerText,
|
||
answerLocked,
|
||
currentFeedbackCorrect,
|
||
examReadyToSubmit,
|
||
canEnterResultStage,
|
||
latestExamFeedback,
|
||
latestSettledResult,
|
||
answerRecords,
|
||
completionDate,
|
||
summaryPoints,
|
||
summaryChecklist,
|
||
learnerProgressPercent,
|
||
correctCount,
|
||
wrongCount,
|
||
isPassed,
|
||
currentUserName,
|
||
currentUserEmployeeId,
|
||
currentUserDepartment,
|
||
hrKeyword,
|
||
hrDepartmentFilter,
|
||
hrStatusFilter,
|
||
hrTypeFilter,
|
||
departmentOptions,
|
||
filteredRecords,
|
||
stats,
|
||
hrTrainingTab,
|
||
leanStats,
|
||
leanRows,
|
||
leanDashboardTaskId,
|
||
selectLeanDashboardPeriod,
|
||
learnerChatPrompt,
|
||
newSessionReminderMessage,
|
||
shouldShowNewSessionReminder,
|
||
learnerAssistantMessage,
|
||
managementChatPrompt,
|
||
markVideoCompleted,
|
||
startExam,
|
||
selectAnswer,
|
||
submitTextAnswer,
|
||
syncExamQuestionIndex,
|
||
moveToNextQuestion,
|
||
submitExam,
|
||
restartExam,
|
||
setSafetyStage,
|
||
exportRecords,
|
||
loadLeanTraining,
|
||
markLeanVideoWatched,
|
||
submitLeanTrainingCompletion,
|
||
remindLeanTrainingMember,
|
||
showVideoModal,
|
||
videoUrl,
|
||
startMaterialTimer,
|
||
stopMaterialTimer,
|
||
currentViewingMaterialId,
|
||
currentViewingMaterialRequiredDuration,
|
||
currentTrainingAgentId,
|
||
};
|
||
}
|