feat(training): 培训配置改造
This commit is contained in:
1 parent
d21c83433e
commit
15225ef1ce
15 files changed
+602
-56
No files matched your search
@@ -1,7 +1,10 @@
|
||||
"""
|
||||
backend/app/services/training_config_service.py
|
||||
|
||||
用途:提供培训配置 CRUD、三级资料绑定与员工培训知识库候选资料查询。
|
||||
依赖:培训、AgentGuide 与知识库 ORM 模型,以及统一业务异常。
|
||||
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照。
|
||||
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照;
|
||||
同时在 settings 中统一维护培训进度项与学员侧文案配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,11 +25,35 @@ RESOURCE_TYPES = {"agent_guide", "kb_document_version", "inline_questions"}
|
||||
CONFIG_STATUSES = {"draft", "published", "archived"}
|
||||
TRAINING_LEVELS = {"company", "department", "team"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
GENERIC_PROGRESS_STAGES = ("video", "summary", "exam", "result")
|
||||
SAFETY_PROGRESS_STAGES = ("company", "department", "team", "exam")
|
||||
TRAINING_TYPE_ALIASES = {
|
||||
"入职培训": "onboarding",
|
||||
"新人培训": "onboarding",
|
||||
"安全培训": "safety",
|
||||
}
|
||||
DEFAULT_TRAINING_SETTINGS: dict[str, dict[str, Any]] = {
|
||||
"onboarding": {
|
||||
"progress_items": [
|
||||
{"stage": "video", "label": "观看视频"},
|
||||
{"stage": "summary", "label": "复盘知识点"},
|
||||
{"stage": "exam", "label": "逐题考试"},
|
||||
{"stage": "result", "label": "结算结果"},
|
||||
],
|
||||
"progress_hint_text": "按 HR 要求完成视频、知识点、考试三个环节后才能视为完成。",
|
||||
"step_intro_text": "第一步:观看培训视频\n员工先完成入职培训视频学习,再进入知识点复盘和考试环节。",
|
||||
},
|
||||
"safety": {
|
||||
"progress_items": [
|
||||
{"stage": "company", "label": "公司级安全培训"},
|
||||
{"stage": "department", "label": "部门级安全培训"},
|
||||
{"stage": "team", "label": "班组级安全培训"},
|
||||
{"stage": "exam", "label": "统一考试"},
|
||||
],
|
||||
"progress_hint_text": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料或视频后,进入 1 次统一考试,90 分及格方可结业。",
|
||||
"step_intro_text": "第一步:完成公司级安全教育\n员工需先完成公司级安全教育资料学习,再依次进入部门级、班组级和统一考试环节。",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _normalize_type_code(value: Any) -> str:
|
||||
@@ -65,6 +92,94 @@ def _required_int(value: Any, field: str) -> int:
|
||||
return parsed
|
||||
|
||||
|
||||
def _allowed_progress_stages(training_type: str) -> tuple[str, ...]:
|
||||
return SAFETY_PROGRESS_STAGES if training_type == "safety" else GENERIC_PROGRESS_STAGES
|
||||
|
||||
|
||||
def _normalize_copy_text(field: str, value: Any) -> str | None:
|
||||
"""
|
||||
清洗培训工作区的可编辑长文本字段。
|
||||
|
||||
用途:统一校验进度说明和步骤引导文案长度,兼容历史空值读写逻辑。
|
||||
参数约束:允许空值;若传入非空内容则去首尾空白且长度不得超过 500 字符。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
if len(text) > 500:
|
||||
raise ValidationError(f"{field} exceeds max length", details={"field": field, "max_length": 500})
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_progress_items(value: Any, training_type: str) -> list[dict[str, str]]:
|
||||
"""
|
||||
规范培训进度项配置。
|
||||
|
||||
用途:让后台保存的进度项始终携带稳定 stage 编码,供学员侧按配置动态渲染流程卡片。
|
||||
参数约束:允许空数组;每项必须包含唯一 stage 和非空 label。
|
||||
"""
|
||||
if value in (None, ""):
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError("progress_items must be an array", details={"field": "settings.progress_items"})
|
||||
|
||||
allowed_stages = set(_allowed_progress_stages(training_type))
|
||||
seen_stages: set[str] = set()
|
||||
normalized: list[dict[str, str]] = []
|
||||
for index, item in enumerate(value):
|
||||
if not isinstance(item, dict):
|
||||
raise ValidationError("progress_items item must be an object", details={"field": "settings.progress_items", "index": index})
|
||||
stage = str(item.get("stage") or item.get("key") or "").strip()
|
||||
label = str(item.get("label") or item.get("title") or "").strip()
|
||||
if stage not in allowed_stages:
|
||||
raise ValidationError(
|
||||
"progress_items stage is invalid",
|
||||
details={"field": "settings.progress_items.stage", "index": index, "allowed": sorted(allowed_stages)},
|
||||
)
|
||||
if stage in seen_stages:
|
||||
raise ValidationError("progress_items contains duplicate stage", details={"field": "settings.progress_items.stage", "index": index})
|
||||
if not label:
|
||||
raise ValidationError("progress_items label is required", details={"field": "settings.progress_items.label", "index": index})
|
||||
if len(label) > 100:
|
||||
raise ValidationError("progress_items label exceeds max length", details={"field": "settings.progress_items.label", "index": index, "max_length": 100})
|
||||
seen_stages.add(stage)
|
||||
normalized.append({"stage": stage, "label": label})
|
||||
return normalized
|
||||
|
||||
|
||||
def _normalize_settings(training_type: str, value: Any, *, include_defaults: bool) -> dict[str, Any]:
|
||||
"""
|
||||
规范培训配置 settings 并按需注入存量默认值。
|
||||
|
||||
用途:统一维护发布配置中的工作区文本与进度项,避免管理端与学员端各自拼装字段。
|
||||
核心逻辑:先保留历史设置,再清洗新增字段;对 onboarding / safety 可按读取场景补默认值,保证旧配置展示不回退为空。
|
||||
"""
|
||||
settings = dict(value) if isinstance(value, dict) else {}
|
||||
normalized = {**settings}
|
||||
|
||||
if "progress_items" in settings:
|
||||
normalized["progress_items"] = _normalize_progress_items(settings.get("progress_items"), training_type)
|
||||
elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS:
|
||||
normalized["progress_items"] = [dict(item) for item in DEFAULT_TRAINING_SETTINGS[training_type]["progress_items"]]
|
||||
|
||||
progress_hint_text = _normalize_copy_text("settings.progress_hint_text", settings.get("progress_hint_text"))
|
||||
step_intro_text = _normalize_copy_text("settings.step_intro_text", settings.get("step_intro_text"))
|
||||
|
||||
if progress_hint_text is not None:
|
||||
normalized["progress_hint_text"] = progress_hint_text
|
||||
elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS:
|
||||
normalized["progress_hint_text"] = DEFAULT_TRAINING_SETTINGS[training_type]["progress_hint_text"]
|
||||
|
||||
if step_intro_text is not None:
|
||||
normalized["step_intro_text"] = step_intro_text
|
||||
elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS:
|
||||
normalized["step_intro_text"] = DEFAULT_TRAINING_SETTINGS[training_type]["step_intro_text"]
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _resource_payload(resource: TrainingConfigResource) -> dict[str, Any]:
|
||||
data = {
|
||||
"id": resource.id,
|
||||
@@ -95,6 +210,7 @@ def _resource_payload(resource: TrainingConfigResource) -> dict[str, Any]:
|
||||
|
||||
|
||||
def serialize_training_config(config: TrainingConfig) -> dict[str, Any]:
|
||||
settings = _normalize_settings(config.training_type, config.settings, include_defaults=True)
|
||||
return {
|
||||
"id": config.id,
|
||||
"training_type": config.training_type,
|
||||
@@ -102,7 +218,7 @@ def serialize_training_config(config: TrainingConfig) -> dict[str, Any]:
|
||||
"version": config.version,
|
||||
"status": config.status,
|
||||
"pass_score": config.pass_score,
|
||||
"settings": config.settings or {},
|
||||
"settings": settings,
|
||||
"published_at": config.published_at.isoformat() if config.published_at else None,
|
||||
"created_at": config.created_at.isoformat() if config.created_at else None,
|
||||
"updated_at": config.updated_at.isoformat() if config.updated_at else None,
|
||||
@@ -158,7 +274,7 @@ def _apply(config: TrainingConfig, data: dict[str, Any], *, user_id: int | None)
|
||||
if "settings" in data:
|
||||
if not isinstance(data["settings"], dict):
|
||||
raise ValidationError("settings must be an object", details={"field": "settings"})
|
||||
config.settings = data["settings"]
|
||||
config.settings = _normalize_settings(training_type, data["settings"], include_defaults=False)
|
||||
if "status" in data:
|
||||
status = str(data["status"]).strip()
|
||||
if status not in CONFIG_STATUSES:
|
||||
|
||||
@@ -167,6 +167,9 @@
|
||||
|
||||
- 管理端按公司级、部门级、班组级三级卡片独立增删培训资料,每条资料保存明确的 `training_level`。
|
||||
- 知识库候选仅允许启用的“员工培训”分组中未删除文档的当前版本,员工端按当前 `safetyStage` 动态过滤并展示对应资料。
|
||||
- 培训管理后台需支持按培训类型配置学员侧 `progress_items`、`progress_hint_text` 与 `step_intro_text`,用于动态渲染培训进度流程和步骤引导文案。
|
||||
- 学员侧仅在后台返回有效 `progress_items` 时渲染培训进度模块;若未配置任何进度项,则整个进度模块隐藏,不显示默认占位内容。
|
||||
- 入职培训、安全培训等存量培训类型需自动补齐预设进度说明与步骤引导文案,保证改造前后的学员体验一致。
|
||||
|
||||
### 3.x.1 Excel/CSV 知识库分段补充需求
|
||||
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
|
||||
## 新人培训 Agent
|
||||
|
||||
<<<<<<< Updated upstream
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| -------------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
@@ -66,6 +67,23 @@
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见[docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
=======
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 |
|
||||
| Chat 附件发送前预览 | 已实现 | 附件列表显示在输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;支持右上角删除,上传中保护删除,发货通知保留解析重试与重复处理入口 |
|
||||
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
|
||||
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
|
||||
| 培训 HR 统计问答兜底 | 已实现 | “员工培训”聊天页中,HR 管理员提问参训人数、通过率、未完成名单、本月成绩统计及考试明细等固定统计问题时,优先走后端本地统计兜底;明细列表会把培训阶段映射为中文(观看视频/知识点复盘/逐题考试/结束),并统一把考试时间、完成时间格式化为年月日,避免当前 Dify 工作流 SQL 改写异常导致问答失败 |
|
||||
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料 |
|
||||
| 培训工作区流程文案配置 | 已实现 | `TrainingConfig.settings` 新增 `progress_items`、`progress_hint_text`、`step_intro_text`;管理端可维护培训进度项和步骤引导文案,学员侧按配置动态渲染,未配置进度项时整体隐藏模块;入职培训和安全培训自动补默认文案,兼容存量体验 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
>>>>>>> Stashed changes
|
||||
|
||||
## 1. 功能总览
|
||||
|
||||
|
||||
+8
-2
@@ -1321,9 +1321,15 @@ Dify
|
||||
- `summary_points`:知识点复盘数组
|
||||
- `summary_checklist`:考前必知数组
|
||||
- `question_bank`:结构化题库(`id/type/prompt/answer/explanation/options`)
|
||||
- 培训配置管理页新增工作区文案字段,统一保存在 `TrainingConfig.settings`:
|
||||
- `progress_items`:学员侧进度项数组,通用培训按 `video/summary/exam/result` 解释,安全培训按 `company/department/team/exam` 解释
|
||||
- `progress_hint_text`:培训进度说明文案,最长 500 字
|
||||
- `step_intro_text`:步骤引导文案,最长 500 字
|
||||
- 员工培训工作区读取顺序:
|
||||
1. 优先读取 `extra_config.training_config`
|
||||
2. 若某项未配置,则仅该项回退到前端默认值,保证旧 Agent 不因缺字段而失效
|
||||
1. 优先读取已发布 `TrainingConfig.settings`
|
||||
2. 若未命中发布配置,再兼容读取 `extra_config.training_config`
|
||||
3. 对入职培训、安全培训的存量配置,后端序列化阶段自动补默认进度说明和步骤引导文案,避免旧数据出现空白
|
||||
- 学员侧通用培训进度模块只根据 `progress_items` 动态渲染;当该数组为空时,整个进度模块隐藏,避免显示静态默认流程。
|
||||
- 题库题量改为后台可配后,前端分数计算改为“按当前题量折算百分制”,不再硬编码每题 5 分。
|
||||
- 管理端支持从已上传并标记为 `training_exam_pdf` 的指南 PDF 解析题库:
|
||||
1. 后端按 `guide_id` 读取 PDF 文本
|
||||
|
||||
@@ -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 未配置专属视频,则回退到默认地址。
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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": "วิเคราะห์คลังข้อสอบไม่สำเร็จ",
|
||||
|
||||
@@ -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": "题库解析失败",
|
||||
|
||||
@@ -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": "題庫解析失敗",
|
||||
|
||||
Reference in new issue
Block a user