feat(training): 培训模块改造!
This commit is contained in:
1 parent
57652ae581
commit
5f713f2c0c
11 files changed
+226
-51
No files matched your search
@@ -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():
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -9,6 +9,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
|
||||
@@ -27,6 +29,32 @@ TRAINING_TYPE_ALIASES = {
|
||||
}
|
||||
|
||||
|
||||
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:
|
||||
try:
|
||||
parsed = int(value)
|
||||
@@ -92,7 +120,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 +142,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
|
||||
@@ -215,8 +243,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -242,7 +242,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;
|
||||
}
|
||||
|
||||
+14
-4
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -207,7 +207,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],
|
||||
@@ -660,24 +660,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,7 +686,7 @@ 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 class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
|
||||
@@ -744,6 +740,23 @@ const currentSafetyStageText = computed(() => {
|
||||
<p class="mt-1 text-sm leading-6 text-secondary">{{ $t('chat.training.video.description') }}</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">
|
||||
@@ -1443,8 +1456,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 +1516,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 +1620,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>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingConfig,
|
||||
getMyTrainingProgress,
|
||||
getMyTrainingTypes,
|
||||
getTrainingStats,
|
||||
listTrainingRecords,
|
||||
saveMyTrainingProgress,
|
||||
@@ -32,6 +33,7 @@ import type {
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
TrainingType,
|
||||
TrainingTypeOption,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
@@ -68,10 +70,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 +107,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');
|
||||
@@ -369,6 +372,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 +577,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 +586,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 +803,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingTypes();
|
||||
void loadTrainingConfig();
|
||||
void loadTrainingProgress();
|
||||
},
|
||||
@@ -974,7 +1009,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}%`,
|
||||
@@ -1126,6 +1161,8 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
publishedSafetySummary,
|
||||
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';
|
||||
|
||||
|
||||
Reference in new issue
Block a user