feat(training): 培训配置改造

This commit is contained in:
runny committed 2026-09-03 08:45:05 +08:00
1 parent d21c83433e
commit 15225ef1ce
15 files changed
+602 -56

No files matched your search

@@ -35,7 +35,15 @@ import {
parseAdminTrainingQuestionBank,
updateAdminTrainingConfig,
} from '../../api/admin.api';
import type { TrainingConfig, TrainingConfigPayload, TrainingLevel } from '../../types/training-config.types';
import type {
GenericTrainingStage,
SafetyTrainingStage,
TrainingConfig,
TrainingConfigPayload,
TrainingConfigSettings,
TrainingLevel,
TrainingProgressItem,
} from '../../types/training-config.types';
import TrainingTypeFormModal from './components/TrainingTypeFormModal.vue';
const { t } = useI18n();
@@ -93,6 +101,25 @@ const sectionItems = computed(() => [
const publishedCount = computed(() => configs.value.filter((config) => config.status === 'published').length);
const resourceCount = computed(() => contentResources.value.length);
const configuredLevelCount = computed(() => trainingLevels.filter((level) => resourcesByLevel(level).length > 0).length);
const genericProgressStageOptions: Array<{ value: GenericTrainingStage; label: string }> = [
{ value: 'video', label: t('admin.trainingConfig.progressStages.video') },
{ value: 'summary', label: t('admin.trainingConfig.progressStages.summary') },
{ value: 'exam', label: t('admin.trainingConfig.progressStages.exam') },
{ value: 'result', label: t('admin.trainingConfig.progressStages.result') },
];
const safetyProgressStageOptions: Array<{ value: SafetyTrainingStage; label: string }> = [
{ value: 'company', label: t('admin.trainingConfig.progressStages.company') },
{ value: 'department', label: t('admin.trainingConfig.progressStages.department') },
{ value: 'team', label: t('admin.trainingConfig.progressStages.team') },
{ value: 'exam', label: t('admin.trainingConfig.progressStages.exam') },
];
const currentProgressStageOptions = computed(() => (
form.value.training_type === 'safety' ? safetyProgressStageOptions : genericProgressStageOptions
));
const progressItems = computed(() => {
const settings = form.value.settings as TrainingConfigSettings;
return Array.isArray(settings.progress_items) ? settings.progress_items : [];
});
/** 创建新增培训类型所需的完整默认配置,确保沿用后端既有字段契约。 */
function emptyForm(): TrainingConfigPayload {
@@ -102,11 +129,34 @@ function emptyForm(): TrainingConfigPayload {
version: 'v1.0',
status: 'draft',
pass_score: 90,
settings: { exam_mode: 'unified', questions: [] },
settings: {
exam_mode: 'unified',
questions: [],
progress_items: [],
progress_hint_text: '',
step_intro_text: '',
},
resources: [],
};
}
/** 确保 settings 为可写对象,便于同一页面持续编辑进度项和文案配置。 */
const ensureSettings = (): TrainingConfigSettings => {
if (!form.value.settings || typeof form.value.settings !== 'object' || Array.isArray(form.value.settings)) {
form.value.settings = {};
}
return form.value.settings as TrainingConfigSettings;
};
/** 确保 progress_items 为数组,避免模板编辑时出现空引用。 */
const ensureProgressItems = (): TrainingProgressItem[] => {
const settings = ensureSettings();
if (!Array.isArray(settings.progress_items)) {
settings.progress_items = [];
}
return settings.progress_items;
};
const showDeleteConfirm = computed({
get: () => deleteTarget.value !== null,
set: (visible: boolean) => {
@@ -185,6 +235,63 @@ const updateSettingText = (key: string, value: string) => {
form.value.settings[key] = value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
};
/** 新增一条培训进度项,按当前培训类型自动选择首个未使用的 stage。 */
const addProgressItem = () => {
const nextStage = currentProgressStageOptions.value.find((option) => !progressItems.value.some((item) => item.stage === option.value))?.value
|| currentProgressStageOptions.value[0]?.value;
if (!nextStage) return;
ensureProgressItems().push({ stage: nextStage, label: '' });
};
/** 删除一条培训进度项。 */
const removeProgressItem = (index: number) => {
ensureProgressItems().splice(index, 1);
};
/** 校验学员侧文案与进度项,避免空值或超长文本写入发布配置。 */
const validateLearnerCopySettings = () => {
const settings = ensureSettings();
const progressHintText = String(settings.progress_hint_text || '').trim();
const stepIntroText = String(settings.step_intro_text || '').trim();
if (!progressHintText) {
msg.warning(t('admin.trainingConfig.messages.progressHintRequired'));
return false;
}
if (!stepIntroText) {
msg.warning(t('admin.trainingConfig.messages.stepIntroRequired'));
return false;
}
if (progressHintText.length > 500 || stepIntroText.length > 500) {
msg.warning(t('admin.trainingConfig.messages.copyTooLong'));
return false;
}
const allowedStages = new Set<TrainingProgressItem['stage']>(
currentProgressStageOptions.value.map((option) => option.value as TrainingProgressItem['stage']),
);
const seenStages = new Set<string>();
const normalizedItems: TrainingProgressItem[] = [];
for (const item of progressItems.value) {
const stage = String(item.stage || '').trim() as TrainingProgressItem['stage'];
const label = String(item.label || '').trim();
if (!stage || !label || !allowedStages.has(stage)) {
msg.warning(t('admin.trainingConfig.messages.progressItemRequired'));
return false;
}
if (seenStages.has(stage)) {
msg.warning(t('admin.trainingConfig.messages.progressStageDuplicate'));
return false;
}
seenStages.add(stage);
normalizedItems.push({ stage, label });
}
settings.progress_hint_text = progressHintText;
settings.step_intro_text = stepIntroText;
settings.progress_items = normalizedItems;
return true;
};
const settingSummaryByStageText = (level: string) => {
const summaries = (form.value.settings.summaryByStage as Record<string, string[]>) || {};
const value = summaries[level];
@@ -267,6 +374,7 @@ const saveType = async () => {
/** 校验题目 JSON,将题库双写至兼容字段后通过既有更新接口保存完整配置。 */
const saveConfig = async () => {
if (!selected.value) return;
if (!validateLearnerCopySettings()) return;
try {
const questions = JSON.parse(questionJsonText.value);
if (!Array.isArray(questions)) throw new Error();
@@ -445,6 +553,52 @@ onMounted(() => void load());
<label class="label-field">{{ t('admin.trainingConfig.fields.passScore') }}<div class="relative mt-2"><input v-model.number="form.pass_score" type="number" min="0" max="100" class="input-field pr-10" /><span class="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-sm text-muted">%</span></div></label>
<label class="label-field md:col-span-2 xl:col-span-2">{{ t('admin.trainingConfig.fields.examMode') }}<select v-model="form.settings.exam_mode" class="select-field mt-2"><option value="unified">{{ t('admin.trainingConfig.examMode.unified') }}</option><option value="per_level">{{ t('admin.trainingConfig.examMode.perLevel') }}</option></select></label>
</div>
<div class="mt-8 space-y-5 rounded-2xl border border-dashed border-default bg-surface-soft/40 p-5">
<div>
<h4 class="text-sm font-semibold text-primary">{{ t('admin.trainingConfig.copySectionTitle') }}</h4>
<p class="mt-1 text-xs leading-5 text-muted">{{ t('admin.trainingConfig.copySectionDesc') }}</p>
</div>
<div class="space-y-3">
<div class="flex items-center justify-between gap-3">
<label class="label-field">{{ t('admin.trainingConfig.fields.progressItems') }}</label>
<button class="btn-secondary btn-sm" type="button" @click="addProgressItem"><Plus class="h-4 w-4" />{{ t('admin.trainingConfig.addProgressItem') }}</button>
</div>
<div v-if="!progressItems.length" class="rounded-xl border border-dashed border-default bg-white px-4 py-6 text-center text-sm text-muted">
{{ t('admin.trainingConfig.progressItemsEmpty') }}
</div>
<div v-else class="space-y-3">
<div v-for="(item, index) in progressItems" :key="`${item.stage}-${index}`" class="grid gap-3 rounded-xl border border-default bg-white p-4 md:grid-cols-[180px_minmax(0,1fr)_auto] md:items-end">
<label class="label-field">
{{ t('admin.trainingConfig.fields.progressStage') }}
<select v-model="item.stage" class="select-field mt-2">
<option v-for="option in currentProgressStageOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
</select>
</label>
<label class="label-field">
{{ t('admin.trainingConfig.fields.progressItemLabel') }}
<input v-model="item.label" maxlength="100" class="input-field mt-2" :placeholder="t('admin.trainingConfig.placeholders.progressItemLabel')" />
</label>
<button class="btn-danger btn-sm md:mb-0.5" type="button" @click="removeProgressItem(index)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
</div>
</div>
</div>
<div class="grid gap-5 xl:grid-cols-2">
<label class="label-field">
<span class="flex items-center justify-between gap-3">
<span>{{ t('admin.trainingConfig.fields.progressHintText') }}</span>
<span class="text-xs text-muted">{{ `${String((form.settings.progress_hint_text || '')).length}/500` }}</span>
</span>
<textarea v-model="form.settings.progress_hint_text" maxlength="500" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.progressHintText')" />
</label>
<label class="label-field">
<span class="flex items-center justify-between gap-3">
<span>{{ t('admin.trainingConfig.fields.stepIntroText') }}</span>
<span class="text-xs text-muted">{{ `${String((form.settings.step_intro_text || '')).length}/500` }}</span>
</span>
<textarea v-model="form.settings.step_intro_text" maxlength="500" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.stepIntroText')" />
</label>
</div>
</div>
</section>
<section id="training-section-resources" class="surface-panel scroll-mt-20 p-5 md:p-7">
@@ -2,10 +2,27 @@
* features/admin/types/training-config.types.ts
* 用途:约束培训配置管理页、候选资料与三级培训资源的数据结构。
* 依赖:admin.api 与 TrainingConfigPage。
* 逻辑:管理端按 training_level 保存资料,员工端发布配置沿用同一层级语义。
* 逻辑:管理端按 training_level 保存资料,员工端发布配置沿用同一层级语义,
* 并通过 settings 承载培训进度项与学员侧文案配置。
*/
export type TrainingConfigStatus = 'draft' | 'published' | 'archived';
export type TrainingLevel = 'company' | 'department' | 'team';
export type GenericTrainingStage = 'video' | 'summary' | 'exam' | 'result';
export type SafetyTrainingStage = 'company' | 'department' | 'team' | 'exam';
export type TrainingProgressStage = GenericTrainingStage | SafetyTrainingStage;
export interface TrainingProgressItem {
stage: TrainingProgressStage;
label: string;
}
export interface TrainingConfigSettings extends Record<string, unknown> {
exam_mode?: 'unified' | 'per_level';
questions?: unknown[];
progress_items?: TrainingProgressItem[];
progress_hint_text?: string;
step_intro_text?: string;
}
export interface TrainingConfigResource {
id?: number;
@@ -26,7 +43,7 @@ export interface TrainingConfig {
version: string;
status: TrainingConfigStatus;
pass_score: number;
settings: Record<string, unknown>;
settings: TrainingConfigSettings;
resources: TrainingConfigResource[];
published_at?: string | null;
}
@@ -37,7 +54,7 @@ export interface TrainingConfigPayload {
version: string;
status: TrainingConfigStatus;
pass_score: number;
settings: Record<string, unknown>;
settings: TrainingConfigSettings;
resources: TrainingConfigResource[];
}
@@ -64,19 +64,39 @@ const showVideoModal = computed({
});
const lastVideoTime = ref(0);
const stageStep = computed(() => {
if (workspace.stage === 'video') return 1;
if (workspace.stage === 'summary') return 2;
if (workspace.stage === 'exam') return 3;
return 4;
const learnerStageOrder = ['video', 'summary', 'exam', 'result'] as const;
const learnerStageIconMap = {
video: PlayCircle,
summary: BookOpen,
exam: ClipboardCheck,
result: ShieldCheck,
} as const;
const currentLearnerStageIndex = computed(() => learnerStageOrder.indexOf(workspace.stage));
const showLearnerProgressModule = computed(() => workspace.learnerProgressItems.length > 0);
const learnerProgressItems = computed(() => workspace.learnerProgressItems.map((item, index) => {
const stageIndex = learnerStageOrder.indexOf(item.stage as typeof learnerStageOrder[number]);
const status = stageIndex >= 0 && currentLearnerStageIndex.value >= 0
? currentLearnerStageIndex.value > stageIndex
? 'completed'
: currentLearnerStageIndex.value === stageIndex
? 'active'
: 'pending'
: 'pending';
return {
...item,
icon: learnerStageIconMap[item.stage as keyof typeof learnerStageIconMap] || BookOpen,
orderLabel: String(index + 1).padStart(2, '0'),
status,
};
}));
const learnerStepIntroTitle = computed(() => {
const [title] = String(workspace.learnerStepIntroText || '').split(/\r?\n/);
return title?.trim() || '';
});
const learnerStepIntroDescription = computed(() => {
const [, ...restLines] = String(workspace.learnerStepIntroText || '').split(/\r?\n/);
return restLines.join('\n').trim();
});
const stageItems = computed(() => ([
{ key: 'video', label: 'chat.training.steps.video', icon: PlayCircle },
{ key: 'summary', label: 'chat.training.steps.summary', icon: BookOpen },
{ key: 'exam', label: 'chat.training.steps.exam', icon: ClipboardCheck },
{ key: 'result', label: 'chat.training.steps.result', icon: ShieldCheck },
]));
const userExpandedOverride = ref<boolean | null>(null);
// HR 管理员与普通员工首次进入培训 Agent 时都默认展开工作区;新建对话仍按既有约束强制收起。
@@ -327,7 +347,9 @@ watch(
const isCompactMode = computed(() => !workspaceExpanded.value);
const isLearnerExamStage = computed(() => !isCompactMode.value && workspace.activeView === 'learner' && workspace.stage === 'exam');
const learnerWorkspaceGridClass = computed(() => (
'grid gap-2.5 p-3 md:grid-cols-[minmax(0,1.7fr)_208px] md:p-4 lg:gap-3 lg:grid-cols-[minmax(0,1.85fr)_220px] 2xl:grid-cols-[minmax(0,1.95fr)_240px]'
workspace.stage === 'exam' || workspace.stage === 'result' || showLearnerProgressModule.value
? 'grid gap-2.5 p-3 md:grid-cols-[minmax(0,1.7fr)_208px] md:p-4 lg:gap-3 lg:grid-cols-[minmax(0,1.85fr)_220px] 2xl:grid-cols-[minmax(0,1.95fr)_240px]'
: 'grid gap-2.5 p-3 md:p-4'
));
const learnerWorkspaceMainClass = computed(() => 'min-w-0 space-y-3');
const progressCardClass = computed(() => 'rounded-2xl border border-default bg-white p-2.5 shadow-sm');
@@ -344,7 +366,7 @@ const compactSummary = computed(() => {
if (workspace.activeView === 'admin') {
return `${workspace.stats.total}${t('chat.training.hr.stats.total')} / ${workspace.stats.passRate}% ${t('chat.training.hr.stats.passRate')}`;
}
if (workspace.stage === 'video') return t('chat.training.video.title');
if (workspace.stage === 'video') return learnerStepIntroTitle.value || t('chat.training.video.title');
if (workspace.stage === 'summary') return t('chat.training.summary.title');
if (workspace.stage === 'exam') {
return t('chat.training.exam.questionCounter', {
@@ -688,14 +710,14 @@ const currentSafetyStageText = computed(() => {
</div>
<template v-else-if="workspace.learnerTab !== 'safety'">
<div :class="learnerWorkspaceMainClass">
<div :class="progressCardClass">
<div v-if="showLearnerProgressModule" :class="progressCardClass">
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
<div>
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
{{ $t('chat.training.progressLabel') }}
</div>
<div class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
{{ $t('chat.training.progressHint') }}
<div v-if="workspace.learnerProgressHintText" class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
{{ workspace.learnerProgressHintText }}
</div>
</div>
<div class="rounded-lg bg-surface-soft px-2.5 py-1 text-center">
@@ -706,27 +728,27 @@ const currentSafetyStageText = computed(() => {
<div class="mt-2 grid grid-cols-2 gap-1 lg:grid-cols-4">
<div
v-for="(item, index) in stageItems"
:key="item.key"
v-for="item in learnerProgressItems"
:key="item.stage"
class="cursor-pointer rounded-xl border px-2 py-1.5 transition hover:border-brand-300"
:class="[
stageStep >= index + 1 ? 'border-brand-200 bg-brand-50/70' : 'border-default bg-surface-soft/70',
canSwitchToStage(String(item.key)) ? 'cursor-pointer hover:border-brand-300' : 'cursor-not-allowed opacity-60',
item.status === 'completed' || item.status === 'active' ? 'border-brand-200 bg-brand-50/70' : 'border-default bg-surface-soft/70',
canSwitchToStage(String(item.stage)) ? 'cursor-pointer hover:border-brand-300' : 'cursor-not-allowed opacity-60',
]"
@click="handleStageCardClick(String(item.key))"
@click="handleStageCardClick(String(item.stage))"
>
<div class="flex items-center gap-2">
<div
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg"
:class="stageStep >= index + 1 ? 'bg-brand-600 text-white' : 'bg-white text-muted'"
:class="item.status === 'completed' || item.status === 'active' ? 'bg-brand-600 text-white' : 'bg-white text-muted'"
>
<component :is="item.icon" class="h-3 w-3" />
</div>
<div class="min-w-0">
<div class="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted">
{{ String(index + 1).padStart(2, '0') }}
{{ item.orderLabel }}
</div>
<div class="whitespace-normal text-[12px] font-medium leading-4 text-primary">{{ $t(item.label) }}</div>
<div class="whitespace-normal text-[12px] font-medium leading-4 text-primary">{{ item.label }}</div>
</div>
</div>
</div>
@@ -734,10 +756,10 @@ const currentSafetyStageText = computed(() => {
</div>
<div v-if="workspace.stage === 'video'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
<div>
<div v-if="learnerStepIntroTitle || learnerStepIntroDescription">
<div>
<h3 class="text-base font-semibold text-primary md:text-lg">{{ $t('chat.training.video.title') }}</h3>
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</p>
<h3 v-if="learnerStepIntroTitle" class="text-base font-semibold text-primary md:text-lg">{{ learnerStepIntroTitle }}</h3>
<p v-if="learnerStepIntroDescription" class="mt-1 whitespace-pre-line text-sm leading-6 text-secondary">{{ learnerStepIntroDescription }}</p>
</div>
</div>
<div class="mt-3">
@@ -983,30 +1005,30 @@ const currentSafetyStageText = computed(() => {
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
<!-- 流程进度面板 (仅在非考试阶段展示) -->
<div v-if="workspace.stage !== 'exam' && workspace.stage !== 'result'" :class="questionNavPanelClass">
<div v-if="showLearnerProgressModule && workspace.stage !== 'exam' && workspace.stage !== 'result'" :class="questionNavPanelClass">
<div class="flex items-center gap-2 mb-3">
<Target class="h-4 w-4 text-brand-600" />
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.progressLabel') }}</div>
</div>
<div class="space-y-2">
<div
v-for="(item, index) in stageItems"
:key="item.key"
v-for="item in learnerProgressItems"
:key="item.stage"
class="flex items-center gap-3 p-2 rounded-lg border transition"
:class="[
stageStep > index + 1 ? 'border-emerald-200 bg-emerald-50/50' :
stageStep === index + 1 ? 'border-brand-300 bg-brand-50' :
item.status === 'completed' ? 'border-emerald-200 bg-emerald-50/50' :
item.status === 'active' ? 'border-brand-300 bg-brand-50' :
'border-slate-100 bg-slate-50/50 opacity-70'
]"
>
<div class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
:class="stageStep > index + 1 ? 'bg-emerald-500 text-white' : stageStep === index + 1 ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
:class="item.status === 'completed' ? 'bg-emerald-500 text-white' : item.status === 'active' ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
>
<CheckCircle2 v-if="stageStep > index + 1" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
<CheckCircle2 v-if="item.status === 'completed'" class="h-4 w-4" />
<span v-else class="text-xs font-bold">{{ Number(item.orderLabel) }}</span>
</div>
<div class="min-w-0 flex-1">
<div class="text-xs font-semibold" :class="stageStep === index + 1 ? 'text-brand-700' : 'text-slate-700'">{{ $t(item.label) }}</div>
<div class="text-xs font-semibold" :class="item.status === 'active' ? 'text-brand-700' : 'text-slate-700'">{{ item.label }}</div>
</div>
</div>
</div>
@@ -2,7 +2,8 @@
* features/chat/composables/useTrainingWorkspace.ts
* 用途:封装员工培训 Agent 的工作区状态,包括学员考试流、进度持久化与 HR 真实统计导出。
* 依赖:Vue reactivity、vue-i18n、training.api,以及 training.types。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端,聊天区只保留问答能力。
* 逻辑:仅在培训 Agent 下启用;学员端按“视频 -> 知识点 -> 一题一答 -> 结算”推进,并把进度同步到后端;
* 非安全培训页额外按后台配置动态渲染进度项与步骤说明文案。
*/
import { computed, ref, watch, type ComputedRef } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -39,6 +40,8 @@ import type {
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
matchesTrainingAgent,
resolveLearnerCopyText,
resolveLearnerProgressItems,
resolveTrainingContentConfig,
resolveSafetyTrainingVideoGuide,
type TrainingGuideLike,
@@ -269,6 +272,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
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);
@@ -1159,6 +1165,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hasPublishedTrainingConfig,
publishedTrainingMaterials,
publishedSafetySummary,
learnerProgressItems,
learnerProgressHintText,
learnerStepIntroText,
activeView,
learnerTab,
trainingTypes,
@@ -62,6 +62,11 @@ export interface TrainingPublishedConfigResource {
} | null;
}
export interface TrainingProgressItem {
stage: string;
label: string;
}
export interface TrainingPublishedConfig {
id: number;
trainingType: TrainingType;
@@ -1,9 +1,9 @@
/**
* features/chat/training/trainingWorkspace.utils.test.ts
* 用途:锁定培训工作区 Agent 识别契约(content_profile / extra_config,非名称)。
* 用途:锁定培训工作区 Agent 识别契约,以及培训进度项/文本配置的解析规则。
*/
import { describe, expect, it } from 'vitest';
import { matchesTrainingAgent } from './trainingWorkspace.utils';
import { matchesTrainingAgent, resolveLearnerCopyText, resolveLearnerProgressItems } from './trainingWorkspace.utils';
describe('matchesTrainingAgent', () => {
it('matches handler_config.content_profile=training', () => {
@@ -31,3 +31,61 @@ describe('matchesTrainingAgent', () => {
})).toBe(false);
});
});
describe('resolveLearnerProgressItems', () => {
it('returns configured progress items in order', () => {
expect(resolveLearnerProgressItems({
id: 1,
trainingType: 'custom',
version: 'v1',
passScore: 90,
settings: {
progress_items: [
{ stage: 'video', label: '观看视频' },
{ stage: 'exam', label: '参加考试' },
],
},
resources: [],
})).toEqual([
{ stage: 'video', label: '观看视频' },
{ stage: 'exam', label: '参加考试' },
]);
});
it('filters invalid or duplicate items', () => {
expect(resolveLearnerProgressItems({
id: 1,
trainingType: 'custom',
version: 'v1',
passScore: 90,
settings: {
progress_items: [
{ stage: 'video', label: '观看视频' },
{ stage: 'video', label: '重复步骤' },
{ stage: '', label: '空阶段' },
{ stage: 'summary', label: '' },
],
},
resources: [],
})).toEqual([
{ stage: 'video', label: '观看视频' },
]);
});
});
describe('resolveLearnerCopyText', () => {
it('returns trimmed text when configured', () => {
expect(resolveLearnerCopyText({
id: 1,
trainingType: 'custom',
version: 'v1',
passScore: 90,
settings: { progress_hint_text: ' 按要求完成学习 ' },
resources: [],
}, 'progress_hint_text')).toBe('按要求完成学习');
});
it('returns empty string for missing text', () => {
expect(resolveLearnerCopyText(null, 'step_intro_text')).toBe('');
});
});
@@ -2,9 +2,9 @@
* features/chat/training/trainingWorkspace.utils.ts
* 用途:沉淀新人培训工作区的纯函数规则,便于前端复用与单测。
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库、复盘配置与动态进度文案。
*/
import type { TrainingContentConfig, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
import type { TrainingContentConfig, TrainingProgressItem, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
type TrainingAgentLike = {
name?: string | null;
@@ -153,6 +153,40 @@ const normalizeQuestionBank = (
const DEFAULT_PASS_SCORE = 90;
/**
* 解析学员侧培训进度项。
* AI 触发时机:当工作区需要按后台配置渲染流程卡片时调用;若后台未配置任何有效项,则返回空数组供页面整体隐藏该模块。
*/
export function resolveLearnerProgressItems(publishedConfig?: TrainingPublishedConfig | null): TrainingProgressItem[] {
const settings = asRecord(publishedConfig?.settings);
const rawItems = settings.progress_items;
if (!Array.isArray(rawItems)) return [];
const seenStages = new Set<string>();
return rawItems
.map((item) => {
const raw = asRecord(item);
const stage = String(raw.stage || raw.key || '').trim();
const label = String(raw.label || raw.title || '').trim();
if (!stage || !label || seenStages.has(stage)) return null;
seenStages.add(stage);
return { stage, label };
})
.filter((item): item is TrainingProgressItem => Boolean(item));
}
/**
* 读取学员侧长文本配置。
* AI 触发时机:培训进度说明和步骤引导只在后台返回非空文本时渲染,避免页面出现空占位。
*/
export function resolveLearnerCopyText(
publishedConfig: TrainingPublishedConfig | null | undefined,
key: 'progress_hint_text' | 'step_intro_text',
): string {
const settings = asRecord(publishedConfig?.settings);
return String(settings[key] || '').trim();
}
/**
* 解析培训视频地址。
* AI 触发时机:当培训工作区需要决定播放哪个培训视频时使用,若 Agent 未配置专属视频,则回退到默认地址。
+27 -1
View File
@@ -4962,6 +4962,10 @@
"questionJsonHint": "Enter a JSON array. Saving syncs it to settings and the inline question resource.",
"questionCount": "{count} questions",
"confirmDelete": "Delete this training configuration?",
"copySectionTitle": "Learner flow copy",
"copySectionDesc": "Configure progress items, the progress note, and the step guide copy. If no progress items are configured, the learner page hides the progress module.",
"addProgressItem": "Add progress item",
"progressItemsEmpty": "No progress items are configured. The learner page will hide this module.",
"sections": {
"basicTitle": "Basic Configuration",
"basicDesc": "Set the training name, release version, status, and exam rules",
@@ -4980,7 +4984,10 @@
},
"placeholders": {
"onePerLine": "Enter one item per line",
"oneQuestionPerLine": "Enter one question per line"
"oneQuestionPerLine": "Enter one question per line",
"progressItemLabel": "Example: Watch video",
"progressHintText": "Example: Training is complete only after the video, knowledge review, and exam are all finished.",
"stepIntroText": "Example: Step 1: Watch the training video\nEmployees complete the video first, then move on to knowledge review and the exam."
},
"fields": {
"type": "Training type code",
@@ -4989,11 +4996,25 @@
"status": "Status",
"passScore": "Pass score",
"examMode": "Exam mode",
"progressItems": "Training progress items",
"progressStage": "Mapped stage",
"progressItemLabel": "Progress item label",
"progressHintText": "Training progress note",
"stepIntroText": "Training step guide copy",
"summaryPoints": "Review points",
"summaryChecklist": "Pre-exam checklist",
"employeeQuestions": "Employee FAQs",
"hrQuestions": "HR FAQs"
},
"progressStages": {
"video": "Watch video",
"summary": "Review key points",
"exam": "One-question exam",
"result": "Result",
"company": "Company-level safety training",
"department": "Department-level safety training",
"team": "Team-level safety training"
},
"status": {
"draft": "Draft",
"published": "Published",
@@ -5013,6 +5034,11 @@
"saveFailed": "Failed to save training configuration",
"typeRequired": "Enter the training type code and name",
"invalidQuestions": "Question JSON must be an array",
"progressHintRequired": "Please enter the training progress note",
"stepIntroRequired": "Please enter the training step guide copy",
"copyTooLong": "Training copy cannot exceed 500 characters",
"progressItemRequired": "Please complete every training progress item",
"progressStageDuplicate": "Training progress stages cannot repeat",
"questionSourceRequired": "Select a training exam PDF",
"parseSuccess": "Parsed {count} questions. Review before saving.",
"parseFailed": "Question bank parsing failed",
+27 -1
View File
@@ -4831,6 +4831,10 @@
"questionJsonHint": "ป้อนอาร์เรย์ JSON เมื่อบันทึกระบบจะซิงค์ไปยัง settings และทรัพยากรคำถามในตัว",
"questionCount": "{count} ข้อ",
"confirmDelete": "ลบการกำหนดค่านี้หรือไม่",
"copySectionTitle": "ข้อความฝั่งผู้เรียน",
"copySectionDesc": "กำหนดรายการความคืบหน้า ข้อความอธิบายความคืบหน้า และข้อความแนะนำขั้นตอน หากไม่ได้กำหนดรายการความคืบหน้า หน้าผู้เรียนจะซ่อนโมดูลนี้",
"addProgressItem": "เพิ่มรายการความคืบหน้า",
"progressItemsEmpty": "ยังไม่ได้กำหนดรายการความคืบหน้า หน้าผู้เรียนจะซ่อนโมดูลนี้",
"sections": {
"basicTitle": "การกำหนดค่าพื้นฐาน",
"basicDesc": "ตั้งชื่อการฝึกอบรม เวอร์ชันเผยแพร่ สถานะ และกฎการสอบ",
@@ -4849,7 +4853,10 @@
},
"placeholders": {
"onePerLine": "กรอกหนึ่งรายการต่อบรรทัด",
"oneQuestionPerLine": "กรอกหนึ่งคำถามต่อบรรทัด"
"oneQuestionPerLine": "กรอกหนึ่งคำถามต่อบรรทัด",
"progressItemLabel": "ตัวอย่าง: ดูวิดีโอ",
"progressHintText": "ตัวอย่าง: จะถือว่าเสร็จสิ้นเมื่อทำวิดีโอ ทบทวนความรู้ และข้อสอบครบแล้ว",
"stepIntroText": "ตัวอย่าง: ขั้นตอนที่ 1: ดูวิดีโอการฝึกอบรม\nพนักงานต้องดูวิดีโอก่อน แล้วจึงไปยังการทบทวนความรู้และข้อสอบ"
},
"fields": {
"type": "รหัสประเภทการฝึกอบรม",
@@ -4858,11 +4865,25 @@
"status": "สถานะ",
"passScore": "คะแนนผ่าน",
"examMode": "โหมดการสอบ",
"progressItems": "รายการความคืบหน้าการฝึกอบรม",
"progressStage": "ขั้นตอนที่ผูกไว้",
"progressItemLabel": "ชื่อรายการความคืบหน้า",
"progressHintText": "คำอธิบายความคืบหน้าการฝึกอบรม",
"stepIntroText": "ข้อความแนะนำขั้นตอนการฝึกอบรม",
"summaryPoints": "ประเด็นทบทวน",
"summaryChecklist": "รายการก่อนสอบ",
"employeeQuestions": "คำถามที่พบบ่อยของพนักงาน",
"hrQuestions": "คำถามที่พบบ่อยของ HR"
},
"progressStages": {
"video": "ดูวิดีโอ",
"summary": "ทบทวนความรู้",
"exam": "สอบทีละข้อ",
"result": "ผลลัพธ์",
"company": "การฝึกอบรมความปลอดภัยระดับบริษัท",
"department": "การฝึกอบรมความปลอดภัยระดับแผนก",
"team": "การฝึกอบรมความปลอดภัยระดับทีม"
},
"status": {
"draft": "ฉบับร่าง",
"published": "เผยแพร่แล้ว",
@@ -4882,6 +4903,11 @@
"saveFailed": "บันทึกการกำหนดค่าไม่สำเร็จ",
"typeRequired": "กรอกรหัสและชื่อประเภทการฝึกอบรม",
"invalidQuestions": "JSON คำถามต้องเป็นอาร์เรย์",
"progressHintRequired": "กรอกคำอธิบายความคืบหน้าการฝึกอบรม",
"stepIntroRequired": "กรอกข้อความแนะนำขั้นตอนการฝึกอบรม",
"copyTooLong": "ข้อความการฝึกอบรมต้องไม่เกิน 500 อักขระ",
"progressItemRequired": "กรอกข้อมูลให้ครบทุกแถวของรายการความคืบหน้า",
"progressStageDuplicate": "ขั้นตอนของรายการความคืบหน้าห้ามซ้ำกัน",
"questionSourceRequired": "เลือก PDF ข้อสอบฝึกอบรม",
"parseSuccess": "วิเคราะห์ได้ {count} ข้อ โปรดตรวจสอบก่อนบันทึก",
"parseFailed": "วิเคราะห์คลังข้อสอบไม่สำเร็จ",
+27 -1
View File
@@ -4987,6 +4987,10 @@
"questionCount": "{count} 道题",
"questionBankTitle": "入职培训题库",
"confirmDelete": "确定删除该培训配置吗?",
"copySectionTitle": "学员侧流程文案",
"copySectionDesc": "配置培训进度项、进度说明和步骤引导文案。若未配置进度项,学员侧将隐藏培训进度模块。",
"addProgressItem": "添加进度项",
"progressItemsEmpty": "未配置培训进度项,学员侧将隐藏该模块",
"sections": {
"basicTitle": "基础配置",
"basicDesc": "设置培训名称、发布版本、状态及考试规则",
@@ -5005,7 +5009,10 @@
},
"placeholders": {
"onePerLine": "每行填写一项",
"oneQuestionPerLine": "每行填写一个问题"
"oneQuestionPerLine": "每行填写一个问题",
"progressItemLabel": "例如:观看视频",
"progressHintText": "例如:按 HR 要求完成视频、知识点、考试三个环节后才能视为完成。",
"stepIntroText": "例如:第一步:观看培训视频\n员工先完成入职培训视频学习,再进入知识点复盘和考试环节。"
},
"fields": {
"type": "培训类型编码",
@@ -5014,11 +5021,25 @@
"status": "状态",
"passScore": "及格分数",
"examMode": "考试模式",
"progressItems": "培训进度项",
"progressStage": "对应阶段",
"progressItemLabel": "进度项名称",
"progressHintText": "培训进度说明",
"stepIntroText": "培训步骤引导文案",
"summaryPoints": "复盘要点",
"summaryChecklist": "考前清单",
"employeeQuestions": "员工常见问题",
"hrQuestions": "HR 常见问题"
},
"progressStages": {
"video": "观看视频",
"summary": "复盘知识点",
"exam": "逐题考试",
"result": "结算结果",
"company": "公司级安全培训",
"department": "部门级安全培训",
"team": "班组级安全培训"
},
"status": {
"draft": "草稿",
"published": "已发布",
@@ -5038,6 +5059,11 @@
"saveFailed": "保存培训配置失败",
"typeRequired": "请填写培训类型编码和名称",
"invalidQuestions": "题目 JSON 格式无效,必须是数组",
"progressHintRequired": "请填写培训进度说明",
"stepIntroRequired": "请填写培训步骤引导文案",
"copyTooLong": "培训说明文案不能超过 500 个字符",
"progressItemRequired": "请完整填写每一条培训进度项",
"progressStageDuplicate": "培训进度项的阶段不能重复",
"questionSourceRequired": "请选择培训试题 PDF",
"parseSuccess": "已解析 {count} 道题目,请复核后保存",
"parseFailed": "题库解析失败",
+27 -1
View File
@@ -4836,6 +4836,10 @@
"questionJsonHint": "請輸入 JSON 陣列;儲存時將同步至配置 settings 與內嵌題目資源。",
"questionCount": "{count} 道題",
"confirmDelete": "確定刪除此培訓配置嗎?",
"copySectionTitle": "學員側流程文案",
"copySectionDesc": "配置培訓進度項、進度說明和步驟引導文案。若未配置進度項,學員側將隱藏培訓進度模組。",
"addProgressItem": "新增進度項",
"progressItemsEmpty": "未配置培訓進度項,學員側將隱藏此模組",
"sections": {
"basicTitle": "基礎配置",
"basicDesc": "設定培訓名稱、發佈版本、狀態及考試規則",
@@ -4854,7 +4858,10 @@
},
"placeholders": {
"onePerLine": "每行填寫一項",
"oneQuestionPerLine": "每行填寫一個問題"
"oneQuestionPerLine": "每行填寫一個問題",
"progressItemLabel": "例如:觀看影片",
"progressHintText": "例如:按 HR 要求完成影片、知識點、考試三個環節後才算完成。",
"stepIntroText": "例如:第一步:觀看培訓影片\n員工先完成入職培訓影片學習,再進入知識點複盤和考試環節。"
},
"fields": {
"type": "培訓類型編碼",
@@ -4863,11 +4870,25 @@
"status": "狀態",
"passScore": "及格分數",
"examMode": "考試模式",
"progressItems": "培訓進度項",
"progressStage": "對應階段",
"progressItemLabel": "進度項名稱",
"progressHintText": "培訓進度說明",
"stepIntroText": "培訓步驟引導文案",
"summaryPoints": "複盤要點",
"summaryChecklist": "考前清單",
"employeeQuestions": "員工常見問題",
"hrQuestions": "HR 常見問題"
},
"progressStages": {
"video": "觀看影片",
"summary": "複盤知識點",
"exam": "逐題考試",
"result": "結算結果",
"company": "公司級安全培訓",
"department": "部門級安全培訓",
"team": "班組級安全培訓"
},
"status": {
"draft": "草稿",
"published": "已發佈",
@@ -4887,6 +4908,11 @@
"saveFailed": "儲存培訓配置失敗",
"typeRequired": "請填寫培訓類型編碼和名稱",
"invalidQuestions": "題目 JSON 必須是陣列",
"progressHintRequired": "請填寫培訓進度說明",
"stepIntroRequired": "請填寫培訓步驟引導文案",
"copyTooLong": "培訓說明文案不能超過 500 個字元",
"progressItemRequired": "請完整填寫每一條培訓進度項",
"progressStageDuplicate": "培訓進度項的階段不能重複",
"questionSourceRequired": "請選擇培訓試題 PDF",
"parseSuccess": "已解析 {count} 道題目,請複核後儲存",
"parseFailed": "題庫解析失敗",