!16 Merge branch 'dev' into runny827

Merge pull request !16 from Runny/runny827
This commit is contained in:
sophie authored and Gitee committed 2026-09-07 01:17:28 +00:00
commit 2e17aaa7fc
20 files changed
+810 -107

No files matched your search

+8 -1
View File
@@ -5,7 +5,7 @@ from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.response import ok
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_kb_version
from app.services.training_config_service import create_config, delete_config, list_configs, list_resource_candidates, update_config
from app.services.training_config_service import create_config, delete_config, list_configs, list_resource_candidates, list_training_type_codes, update_config
@admin_bp.route("/training-configs", methods=["GET"])
@@ -14,6 +14,13 @@ def list_training_configs():
return jsonify(list_configs())
@admin_bp.route("/training-configs/types", methods=["GET"])
@require_admin
def list_published_training_types():
"""返回已发布培训类型的编码与名称,供管理端动态展示。"""
return jsonify(list_training_type_codes())
@admin_bp.route("/training-configs/resource-candidates", methods=["GET"])
@require_admin
def list_training_config_resource_candidates():
+14 -1
View File
@@ -22,7 +22,7 @@ from app.services.training_service import (
summarize_training_records,
upsert_user_training_record,
)
from app.services.training_config_service import get_published_config
from app.services.training_config_service import get_published_config, list_training_type_codes
training_user_bp = Blueprint("training_user", __name__)
training_admin_bp = Blueprint("training_admin", __name__)
@@ -58,6 +58,19 @@ def get_my_training_record():
return jsonify(serialize_training_record(record) if record else None)
@training_user_bp.route("/training-types", methods=["GET"])
def list_my_training_types():
"""
返回当前员工可见的已发布培训类型目录。
用途:为员工动态培训 Tabs 和 HR 类型名称映射提供统一的 code/name 数据源。
Returns:
已发布培训类型列表;每项包含非空 code 与管理员配置的展示名称。
"""
_require_user()
return jsonify(list_training_type_codes())
@training_user_bp.route("/training-config", methods=["GET"])
def get_my_training_config():
_require_user()
+154 -9
View File
@@ -1,7 +1,10 @@
"""
backend/app/services/training_config_service.py
用途:提供培训配置 CRUD、三级资料绑定与员工培训知识库候选资料查询。
依赖:培训、AgentGuide 与知识库 ORM 模型,以及统一业务异常。
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照。
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照;
同时在 settings 中统一维护培训进度项与学员侧文案配置。
"""
from __future__ import annotations
@@ -9,6 +12,8 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
import re
from sqlalchemy import select, update
from app.core.errors import NotFoundError, ValidationError
@@ -20,11 +25,61 @@ 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:
"""
校验并标准化培训类型编码。
用途:管理端新增或员工端读取培训类型时统一使用稳定编码,避免名称变化影响培训记录关联。
Args:
value: 培训类型编码;兼容历史中文别名。
Returns:
小写的合法类型编码。
"""
text = TRAINING_TYPE_ALIASES.get(str(value or "").strip(), str(value or "").strip().lower())
if not re.fullmatch(r"[a-z][a-z0-9_-]{0,49}", text):
raise ValidationError("training_type is invalid", details={"field": "training_type"})
return text
def list_training_type_codes() -> list[dict[str, str]]:
"""返回已发布培训类型的编码与名称,供员工端动态加载培训入口。"""
configs = db.session.execute(
select(TrainingConfig.training_type, TrainingConfig.name)
.where(TrainingConfig.status == "published")
.order_by(TrainingConfig.training_type)
).all()
return [{"code": type_code, "name": str(name or "").strip()} for type_code, name in configs]
def _required_int(value: Any, field: str) -> int:
@@ -37,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,
@@ -67,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,
@@ -74,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,
@@ -92,7 +236,7 @@ def _validate_resource(item: dict[str, Any]) -> dict[str, Any]:
raise ValidationError("training_level is invalid", details={"field": "training_level", "allowed": sorted(TRAINING_LEVELS)})
if resource_type != "inline_questions" and not training_level:
raise ValidationError("training_level is required", details={"field": "training_level"})
result = {"resource_type": resource_type, "training_level": training_level, "title": item.get("title"), "required_duration": int(item.get("required_duration") or 0), "sort_order": int(item.get("sort_order") or 0)}
result = {"resource_type": resource_type, "training_level": training_level, "title": str(item.get("title") or "").strip() or None, "required_duration": int(item.get("required_duration") or 0), "sort_order": int(item.get("sort_order") or 0)}
if resource_type == "agent_guide":
result["agent_guide_id"] = _required_int(item.get("agent_guide_id"), "agent_guide_id")
if not db.session.get(AgentGuide, result["agent_guide_id"]):
@@ -114,11 +258,11 @@ def _validate_resource(item: dict[str, Any]) -> dict[str, Any]:
def _apply(config: TrainingConfig, data: dict[str, Any], *, user_id: int | None) -> None:
raw_training_type = str(data.get("training_type") or data.get("type") or config.training_type or "").strip()
training_type = TRAINING_TYPE_ALIASES.get(raw_training_type, raw_training_type.lower())
training_type = _normalize_type_code(raw_training_type)
name = str(data.get("name") or config.name or "").strip()
version = str(data.get("version") or config.version or "").strip()
if training_type not in TRAINING_TYPES:
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(TRAINING_TYPES)})
if not training_type:
raise ValidationError("training_type is invalid", details={"field": "training_type"})
if not name or not version:
raise ValidationError("training_type, name and version are required")
config.training_type, config.name, config.version = training_type, name, version
@@ -130,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:
@@ -215,8 +359,9 @@ def delete_config(config_id: int) -> None:
def get_published_config(training_type: str) -> dict[str, Any] | None:
normalized_type = TRAINING_TYPE_ALIASES.get(str(training_type or "").strip(), str(training_type or "").strip().lower())
if normalized_type not in TRAINING_TYPES:
try:
normalized_type = _normalize_type_code(training_type)
except ValidationError:
return None
config = db.session.execute(
select(TrainingConfig)
+19 -7
View File
@@ -35,11 +35,22 @@ def _default_training_version(training_type: str) -> str:
返回培训类型对应的默认版本号。
Args:
training_type: 培训类型。当前仅允许 onboarding / safety。
training_type: 培训类型编码。
Returns:
默认培训版本字符串。
"""
return "safety-v1" if training_type == "safety" else "onboarding-v1"
return f"{training_type}-v1"
def _configured_training_types() -> set[str]:
"""读取数据库中已配置的培训类型编码,供进度接口动态校验。"""
from app.models import TrainingConfig
return {
str(training_type).strip()
for training_type in db.session.execute(select(TrainingConfig.training_type)).scalars()
if str(training_type or "").strip()
}
def _normalize_training_type(value: Any) -> str:
@@ -47,13 +58,14 @@ def _normalize_training_type(value: Any) -> str:
校验并标准化培训类型。
Args:
value: 前端上传的培训类型,允许空值回退为 onboarding。
value: 前端上传的培训类型编码,允许空值回退为 onboarding。
Returns:
合法的培训类型字符串。
已配置的培训类型编码。
"""
text = str(value or "onboarding").strip() or "onboarding"
if text not in TRAINING_TYPES:
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(TRAINING_TYPES)})
text = str(value or "onboarding").strip().lower() or "onboarding"
allowed = TRAINING_TYPES | _configured_training_types()
if text not in allowed:
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(allowed)})
return text
+44 -1
View File
@@ -655,7 +655,50 @@ def test_non_training_preview_url_keeps_existing_http_fetch_path(monkeypatch):
assert content_type == "application/pdf"
assert error is None
def test_training_admin_permission_can_be_granted_by_feature_permission(client, app):
def test_dynamic_training_type_code_title_cleanup_and_published_type_list(client, app):
"""自定义类型编码应动态可用,资料标题去除首尾空白,列表仅返回已发布类型。"""
with app.app_context():
admin = _create_user(username="training_type_admin", role="admin")
draft = training_config_service.create_config(
{
"training_type": "compliance_training",
"name": "合规培训",
"version": "v1.0",
"status": "draft",
"resources": [],
},
user_id=admin.id,
)
published = training_config_service.create_config(
{
"training_type": "quality-training",
"name": "质量培训",
"version": "v1.0",
"status": "published",
"resources": [
{
"resource_type": "inline_questions",
"title": " 质量考试 ",
"inline_questions": [{"id": "q1"}],
},
],
},
user_id=admin.id,
)
# 关键断言:类型编码被规范化,标题不保留录入空白。
assert draft["training_type"] == "compliance_training"
assert published["training_type"] == "quality_training"
assert published["resources"][0]["title"] == "质量考试"
headers = _auth_headers(admin)
response = client.get("/api/user/training-types", headers=headers)
# 关键断言:发布类型列表可供前端动态选择,草稿不得暴露。
assert response.status_code == 200
assert response.get_json() == [{"code": "quality_training", "name": "质量培训"}]
"""培训 HR 管理能力应支持通过功能权限显式授予普通用户。"""
with app.app_context():
granted_user = _create_user(
+3
View File
@@ -167,6 +167,9 @@
- 管理端按公司级、部门级、班组级三级卡片独立增删培训资料,每条资料保存明确的 `training_level`。
- 知识库候选仅允许启用的“员工培训”分组中未删除文档的当前版本,员工端按当前 `safetyStage` 动态过滤并展示对应资料。
- 培训管理后台需支持按培训类型配置学员侧 `progress_items`、`progress_hint_text` 与 `step_intro_text`,用于动态渲染培训进度流程和步骤引导文案。
- 学员侧仅在后台返回有效 `progress_items` 时渲染培训进度模块;若未配置任何进度项,则整个进度模块隐藏,不显示默认占位内容。
- 入职培训、安全培训等存量培训类型需自动补齐预设进度说明与步骤引导文案,保证改造前后的学员体验一致。
### 3.x.1 Excel/CSV 知识库分段补充需求
+8 -2
View File
@@ -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];
@@ -242,7 +349,7 @@ const saveType = async () => {
'新人培训': 'onboarding',
'安全培训': 'safety',
} as Record<string, string>)[rawType] || rawType.toLowerCase();
if (!['onboarding', 'safety'].includes(typeForm.value.training_type) || !typeForm.value.name.trim()) {
if (!/^[a-z][a-z0-9_-]*$/.test(typeForm.value.training_type) || !typeForm.value.name.trim()) {
msg.warning(t('admin.trainingConfig.messages.typeRequired'));
return;
}
@@ -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">
@@ -1,4 +1,10 @@
<script setup lang="ts">
/**
* features/admin/modules/training-config/components/TrainingTypeFormModal.vue
* 用途:提供培训类型 code 与名称的新增、编辑弹窗。
* 依赖:vue-i18n 与父级培训配置页面的表单状态。
* 逻辑:允许管理员输入符合编码规范的自定义类型 code,并将保存动作交由父级处理。
*/
import { useI18n } from 'vue-i18n';
const props = defineProps<{
@@ -21,10 +27,14 @@ const { t } = useI18n();
<div class="px-5 sm:px-8 py-5 space-y-4 overflow-y-auto">
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.trainingConfig.fields.type') }}</label>
<select v-model="props.form.training_type" class="select-field text-sm">
<option value="onboarding">{{ t('chat.training.safety.tabs.onboarding') }}</option>
<option value="safety">{{ t('chat.training.safety.tabs.safety') }}</option>
</select>
<input
v-model="props.form.training_type"
type="text"
class="input-field text-sm"
maxlength="50"
pattern="[a-z][a-z0-9_-]*"
:placeholder="t('admin.trainingConfig.placeholders.typeCode')"
/>
</div>
<div class="space-y-1.5">
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}</label>
@@ -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[];
}
@@ -16,6 +16,7 @@ import type {
TrainingStage,
TrainingStats,
TrainingType,
TrainingTypeOption,
} from '../training/training.types';
type TrainingRecordApi = {
@@ -224,8 +225,12 @@ function buildQueryString(query: TrainingRecordQuery = {}) {
return params.toString();
}
export async function getMyTrainingTypes(): Promise<TrainingTypeOption[]> {
return requestJson<TrainingTypeOption[]>('/api/user/training-types', authHeaders());
}
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${type}`, authHeaders());
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${encodeURIComponent(type)}`, authHeaders());
return data ? mapTrainingProgressRecord(data) : null;
}
@@ -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 时都默认展开工作区;新建对话仍按既有约束强制收起。
@@ -207,7 +227,7 @@ const printReport = async () => {
const element = document.getElementById('report-modal-content');
const report = currentReportRecord.value;
if (!element || !report) return;
const fileName = `${report.name}_${report.trainingType === 'onboarding' ? t('chat.training.hr.filters.typeOnboarding') : report.trainingType === 'safety' ? t('chat.training.hr.filters.typeSafety') : report.trainingType}_考试报告.pdf`;
const fileName = `${report.name}_${workspace.resolveTrainingTypeName(report.trainingType)}_考试报告.pdf`;
const opt = {
margin: [15, 15, 15, 15] as [number, number, number, number],
@@ -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', {
@@ -660,24 +682,20 @@ const currentSafetyStageText = computed(() => {
</div>
<div v-if="!isCompactMode && workspace.activeView === 'learner'" :class="learnerWorkspaceGridClass">
<!-- 增加顶部 Tab 切换:入职培训 / 安全培训 -->
<!-- 已发布培训类型由后端配置动态提供。 -->
<div class="col-span-full mb-1">
<div class="inline-flex rounded-xl border border-default bg-surface-soft p-1">
<div class="inline-flex flex-wrap rounded-xl border border-default bg-surface-soft p-1">
<button
v-for="trainingType in workspace.trainingTypes"
:key="trainingType.code"
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'onboarding' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'onboarding'"
:class="workspace.learnerTab === trainingType.code ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = trainingType.code"
>
<User class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.onboarding') }}
</button>
<button
class="flex items-center gap-2 rounded-lg px-6 py-2 text-sm font-medium transition"
:class="workspace.learnerTab === 'safety' ? 'bg-white text-brand-700 shadow-sm border border-brand-200' : 'text-secondary hover:text-primary'"
@click="workspace.learnerTab = 'safety'"
>
<ShieldCheck class="h-4 w-4" />
{{ $t('chat.training.safety.tabs.safety') }}
<ShieldCheck v-if="trainingType.code === 'safety'" class="h-4 w-4" />
<User v-else-if="trainingType.code === 'onboarding'" class="h-4 w-4" />
<BookOpen v-else class="h-4 w-4" />
{{ trainingType.name }}
</button>
</div>
</div>
@@ -690,16 +708,16 @@ const currentSafetyStageText = computed(() => {
<div class="mt-3 text-base font-semibold text-primary">{{ $t('chat.training.noContent.title') }}</div>
<div class="mt-1 text-sm">{{ $t('chat.training.noContent.description') }}</div>
</div>
<template v-else-if="workspace.learnerTab === 'onboarding'">
<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">
@@ -710,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>
@@ -738,12 +756,29 @@ 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">
<ul v-if="workspace.publishedTrainingMaterials.length" class="space-y-2">
<li
v-for="material in workspace.publishedTrainingMaterials"
:key="material.id || `${material.resourceType}-${material.sortOrder}`"
class="flex items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50 px-3 py-2.5 cursor-pointer transition hover:bg-slate-100"
@click="handleMaterialClick(material)"
>
<div class="flex min-w-0 items-center gap-2 text-sm font-medium text-primary hover:text-brand-600">
<Video v-if="material.resource?.fileType === 'video'" class="h-4 w-4 text-brand-500" />
<FileText v-else class="h-4 w-4 text-slate-400" />
<span class="truncate">{{ material.title || material.resource?.fileName || $t('chat.training.video.playerTitle') }}</span>
</div>
</li>
</ul>
</div>
<div class="mt-3 relative group cursor-pointer overflow-hidden rounded-2xl border border-default bg-slate-900 shadow-lg aspect-video flex items-center justify-center" @click="showVideoModal = true">
<img src="https://coresg-normal.trae.ai/api/ide/v1/text_to_image?prompt=Professional%20corporate%20training%20video%20cover%2C%20high-quality%2C%20modern%20office%20background%2C%20play%20button%20overlay&image_size=landscape_16_9" class="absolute inset-0 w-full h-full object-cover opacity-60 group-hover:scale-105 transition-transform duration-500" />
<div class="relative z-10 flex flex-col items-center gap-3">
@@ -970,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>
@@ -1443,8 +1478,9 @@ const currentSafetyStageText = computed(() => {
class="w-full rounded-xl border border-default bg-surface px-3 py-2.5 text-sm text-primary outline-none transition focus:border-brand-300"
>
<option value="all">{{ $t('chat.training.hr.filters.allTypes') }}</option>
<option value="onboarding">{{ $t('chat.training.hr.filters.typeOnboarding') }}</option>
<option value="safety">{{ $t('chat.training.hr.filters.typeSafety') }}</option>
<option v-for="trainingType in workspace.trainingTypes" :key="trainingType.code" :value="trainingType.code">
{{ trainingType.name }}
</option>
</select>
</label>
<label>
@@ -1502,7 +1538,7 @@ const currentSafetyStageText = computed(() => {
<tr v-for="record in workspace.filteredRecords" :key="record.id" class="odd:bg-white even:bg-surface-soft/30">
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.joinDate }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.completionDate || '--' }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.trainingType === 'onboarding' ? $t('chat.training.hr.filters.typeOnboarding') : record.trainingType === 'safety' ? $t('chat.training.hr.filters.typeSafety') : (record.trainingType || '--') }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ workspace.resolveTrainingTypeName(record.trainingType) }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.department }}</td>
<td class="border-b border-default px-3 py-2.5 font-medium text-primary">{{ record.name }}</td>
<td class="border-b border-default px-3 py-2.5 text-secondary">{{ record.employeeId }}</td>
@@ -1606,7 +1642,7 @@ const currentSafetyStageText = computed(() => {
<div v-else-if="currentReportRecord">
<!-- Header Info -->
<div class="report-header-info mb-8 rounded-2xl bg-surface-soft p-6">
<h2 class="mb-4 text-center text-2xl font-bold text-primary">{{ currentReportRecord.trainingType === 'onboarding' ? $t('chat.training.hr.filters.typeOnboarding') : currentReportRecord.trainingType === 'safety' ? $t('chat.training.hr.filters.typeSafety') : currentReportRecord.trainingType }} {{ $t('chat.training.hr.report.title') }}</h2>
<h2 class="mb-4 text-center text-2xl font-bold text-primary">{{ workspace.resolveTrainingTypeName(currentReportRecord.trainingType) }} {{ $t('chat.training.hr.report.title') }}</h2>
<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
<div>
<div class="text-xs text-secondary">{{ $t('chat.training.hr.columns.name') }}</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';
@@ -12,6 +13,7 @@ import {
exportTrainingRecords,
getMyTrainingConfig,
getMyTrainingProgress,
getMyTrainingTypes,
getTrainingStats,
listTrainingRecords,
saveMyTrainingProgress,
@@ -32,11 +34,14 @@ import type {
TrainingStage,
TrainingStats,
TrainingType,
TrainingTypeOption,
TrainingWorkspaceView,
} from '@/features/chat/training/training.types';
import {
SAFETY_STAGE_GUIDE_USAGE_MAP,
matchesTrainingAgent,
resolveLearnerCopyText,
resolveLearnerProgressItems,
resolveTrainingContentConfig,
resolveSafetyTrainingVideoGuide,
type TrainingGuideLike,
@@ -68,10 +73,7 @@ export interface UseTrainingWorkspaceOptions {
}
const DEFAULT_PASS_SCORE = 90;
const DEFAULT_TRAINING_VERSION: Record<TrainingType, string> = {
onboarding: 'onboarding-v1',
safety: 'safety-v1',
};
const DEFAULT_TRAINING_VERSION = 'v1.0';
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
@@ -108,7 +110,11 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
const defaultActiveView = computed<TrainingWorkspaceView>(() => (isAdminViewer.value ? 'admin' : 'learner'));
const activeView = ref<TrainingWorkspaceView>('learner');
const learnerTab = ref<TrainingType>('onboarding');
const trainingVersion = ref<string>(DEFAULT_TRAINING_VERSION.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');
@@ -266,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);
@@ -369,6 +378,37 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
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 触发时机:当前端需要严格模拟“未通过必须重考”的培训流程时使用,确保上一轮答题状态不会污染下一轮。
@@ -543,7 +583,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
*/
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
if (!record) {
trainingVersion.value = DEFAULT_TRAINING_VERSION[learnerTab.value];
trainingVersion.value = DEFAULT_TRAINING_VERSION;
examMode.value = 'unified';
resetSafetyProgress('company');
stage.value = 'video';
@@ -552,7 +592,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
latestSettledResult.value = null;
return;
}
trainingVersion.value = record.trainingVersion || DEFAULT_TRAINING_VERSION[learnerTab.value];
trainingVersion.value = record.trainingVersion || publishedConfig.value?.version || DEFAULT_TRAINING_VERSION;
examMode.value = record.examMode || 'unified';
if (learnerTab.value === 'safety') {
safetyStage.value = record.safetyStage || 'company';
@@ -769,6 +809,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
return;
}
isHydrated.value = false;
void loadTrainingTypes();
void loadTrainingConfig();
void loadTrainingProgress();
},
@@ -974,7 +1015,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
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') : hrTypeFilter.value === 'safety' ? t('chat.training.hr.filters.typeSafety') : t('chat.training.hr.filters.typeOnboarding')}`,
`${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}%`,
@@ -1124,8 +1165,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
hasPublishedTrainingConfig,
publishedTrainingMaterials,
publishedSafetySummary,
learnerProgressItems,
learnerProgressHintText,
learnerStepIntroText,
activeView,
learnerTab,
trainingTypes,
resolveTrainingTypeName,
trainingVersion,
examMode,
safetyStage,
@@ -5,7 +5,12 @@
* 逻辑:统一约束“多培训类型学员流程”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
*/
export type TrainingType = 'onboarding' | 'safety';
export type TrainingType = string;
export interface TrainingTypeOption {
code: TrainingType;
name: string;
}
export type TrainingStage = 'video' | 'summary' | 'exam' | 'result';
@@ -57,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": "題庫解析失敗",