feat(安全培训): 新增员工安全培训相关功能
This commit is contained in:
1 parent
cbc3cb959f
commit
8e5c57790c
50 files changed
+3769
-87
No files matched your search
@@ -31,5 +31,6 @@ import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
|
||||
import app.api.admin.linked_services # noqa: F401
|
||||
import app.api.admin.procurement_contract # noqa: F401
|
||||
import app.api.admin.training_configs # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -0,0 +1,51 @@
|
||||
from flask import g, jsonify, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
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
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs", methods=["GET"])
|
||||
@require_admin
|
||||
def list_training_configs():
|
||||
return jsonify(list_configs())
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs/resource-candidates", methods=["GET"])
|
||||
@require_admin
|
||||
def list_training_config_resource_candidates():
|
||||
return jsonify(list_resource_candidates())
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs/question-bank/parse", methods=["POST"])
|
||||
@require_admin
|
||||
def parse_training_config_question_bank():
|
||||
data = request.get_json(silent=True) or {}
|
||||
version_id = data.get("kb_document_version_id")
|
||||
try:
|
||||
version_id = int(version_id)
|
||||
except (TypeError, ValueError):
|
||||
version_id = 0
|
||||
return ok(parse_training_question_bank_from_kb_version(version_id), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs", methods=["POST"])
|
||||
@require_admin
|
||||
def create_training_config():
|
||||
return jsonify(create_config(request.get_json(silent=True) or {}, getattr(get_current_user(), "id", None))), 201
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs/<int:config_id>", methods=["PUT"])
|
||||
@require_admin
|
||||
def update_training_config(config_id: int):
|
||||
return jsonify(update_config(config_id, request.get_json(silent=True) or {}, getattr(get_current_user(), "id", None)))
|
||||
|
||||
|
||||
@admin_bp.route("/training-configs/<int:config_id>", methods=["DELETE"])
|
||||
@require_admin
|
||||
def delete_training_config(config_id: int):
|
||||
delete_config(config_id)
|
||||
return jsonify({"success": True})
|
||||
@@ -8,6 +8,7 @@ api/chat/preview_support.py
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from urllib.parse import urljoin
|
||||
|
||||
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
@@ -65,6 +66,28 @@ def _is_allowed_share_path(target_url: str) -> bool:
|
||||
]
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_internal_relative_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
判断是否为当前站点内部的根路径预览地址。
|
||||
|
||||
用途:培训资料里的知识库文件会下发 `/api/kb/.../source-file` 这类相对地址,
|
||||
预览代理必须把它视为“当前站点受保护资源”,而不是误判成非法外链。
|
||||
"""
|
||||
raw = str(target_url or '').strip()
|
||||
return raw.startswith('/api/')
|
||||
|
||||
def _resolve_internal_preview_url(target_url: str) -> str:
|
||||
"""
|
||||
将站内相对预览地址补成完整绝对 URL,供 requests 访问。
|
||||
|
||||
AI 触发时机:当预览接口收到 `/api/...` 形式的受保护资源时使用,
|
||||
必须补齐当前请求 Host,才能把登录态透传给后续内部文件下载接口。
|
||||
"""
|
||||
raw = str(target_url or '').strip()
|
||||
if not raw or not _is_internal_relative_preview_url(raw) or not has_request_context():
|
||||
return raw
|
||||
return urljoin(request.host_url, raw)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
预览代理 URL 白名单校验。
|
||||
@@ -76,6 +99,8 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
try:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
if _is_internal_relative_preview_url(target_url) and has_request_context():
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ('http', 'https'):
|
||||
return False
|
||||
@@ -117,6 +142,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import time
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
file_url = _resolve_internal_preview_url(file_url)
|
||||
if _is_allowed_share_path(file_url):
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
|
||||
@@ -22,6 +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
|
||||
|
||||
training_user_bp = Blueprint("training_user", __name__)
|
||||
training_admin_bp = Blueprint("training_admin", __name__)
|
||||
@@ -52,10 +53,17 @@ def _require_training_admin():
|
||||
def get_my_training_record():
|
||||
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||
user = _require_user()
|
||||
record = get_user_training_record(user.id)
|
||||
training_type = request.args.get("type") or "onboarding"
|
||||
record = get_user_training_record(user.id, training_type)
|
||||
return jsonify(serialize_training_record(record) if record else None)
|
||||
|
||||
|
||||
@training_user_bp.route("/training-config", methods=["GET"])
|
||||
def get_my_training_config():
|
||||
_require_user()
|
||||
return jsonify(get_published_config(request.args.get("type") or "onboarding"))
|
||||
|
||||
|
||||
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||
def save_my_training_record():
|
||||
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||
@@ -72,9 +80,10 @@ def list_admin_training_records():
|
||||
keyword = request.args.get("keyword")
|
||||
department = request.args.get("department")
|
||||
status = request.args.get("status")
|
||||
training_type = request.args.get("type")
|
||||
|
||||
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||
all_records = list_training_records()
|
||||
result = list_training_records(keyword=keyword, department=department, status=status, training_type=training_type)
|
||||
all_records = list_training_records(training_type=training_type)
|
||||
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||
|
||||
page = max(1, request.args.get("page", type=int) or 1)
|
||||
@@ -104,6 +113,7 @@ def get_admin_training_stats():
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
training_type=request.args.get("type"),
|
||||
)
|
||||
return jsonify(summarize_training_records(result.records))
|
||||
|
||||
@@ -116,6 +126,7 @@ def export_admin_training_records():
|
||||
keyword=request.args.get("keyword"),
|
||||
department=request.args.get("department"),
|
||||
status=request.args.get("status"),
|
||||
training_type=request.args.get("type"),
|
||||
)
|
||||
file_data, file_name = export_training_records_excel(result.records)
|
||||
return send_file(
|
||||
|
||||
@@ -176,7 +176,7 @@ from app.models.shipping_inventory_preparation import (
|
||||
ShippingInventoryPreparationSourceAttempt,
|
||||
)
|
||||
from app.models.shipping_inventory_mapping import ShippingInventoryMapping
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.training import TrainingRecord, TrainingConfig, TrainingConfigResource
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.voucher_check import VoucherCheckInvoiceState, VoucherCheckRunItem
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
@@ -333,6 +333,8 @@ __all__ = [
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
'TrainingRecord',
|
||||
'TrainingConfig',
|
||||
'TrainingConfigResource',
|
||||
'MaintenanceDevice',
|
||||
'MaintenanceRecord',
|
||||
'MaintenanceAuditLog',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/training.py
|
||||
|
||||
用途:定义新人入职培训记录模型,承载学员当前培训进度、成绩结算与 HR 统计来源。
|
||||
用途:定义员工培训记录模型,承载入职培训/安全培训的进度、考试结果与 HR 统计来源。
|
||||
依赖:models.base.Base、SQLAlchemy 映射、users 主表外键。
|
||||
逻辑:每个用户维护一条当前培训记录;前端学习流与管理端统计都基于该表读写。
|
||||
逻辑:每个用户在每种培训类型下维护一条当前记录;P0 阶段先为安全培训补齐三级状态、考试模式和版本号持久化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,19 +11,25 @@ from __future__ import annotations
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String
|
||||
from sqlalchemy import Boolean, Date, DateTime, ForeignKey, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class TrainingRecord(Base):
|
||||
"""新人入职培训当前记录。"""
|
||||
"""培训记录。"""
|
||||
|
||||
__tablename__ = "training_records"
|
||||
__table_args__ = (UniqueConstraint("user_id", "training_type", name="uq_user_training_type"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), unique=True, index=True, nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), index=True, nullable=False)
|
||||
training_type: Mapped[str] = mapped_column(String(50), nullable=False, default="onboarding", index=True)
|
||||
training_version: Mapped[str] = mapped_column(String(64), nullable=False, default="onboarding-v1", index=True)
|
||||
exam_mode: Mapped[str] = mapped_column(String(20), nullable=False, default="unified")
|
||||
safety_stage: Mapped[Optional[str]] = mapped_column(String(20), nullable=True, index=True)
|
||||
safety_progress: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
employee_id: Mapped[Optional[str]] = mapped_column(String(50), nullable=True, index=True)
|
||||
name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100), nullable=True, index=True)
|
||||
@@ -45,4 +51,46 @@ class TrainingRecord(Base):
|
||||
index=True,
|
||||
)
|
||||
|
||||
user = relationship("User", back_populates="training_record")
|
||||
user = relationship("User", back_populates="training_records")
|
||||
|
||||
|
||||
class TrainingConfig(Base):
|
||||
__tablename__ = "training_configs"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
training_type: Mapped[str] = mapped_column(String(50), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(100), nullable=False)
|
||||
version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(20), nullable=False, default="draft", index=True)
|
||||
pass_score: Mapped[int] = mapped_column(Integer, nullable=False, default=90)
|
||||
settings: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
resources: Mapped[list["TrainingConfigResource"]] = relationship(
|
||||
"TrainingConfigResource", back_populates="config", cascade="all, delete-orphan", order_by="TrainingConfigResource.sort_order"
|
||||
)
|
||||
|
||||
|
||||
class TrainingConfigResource(Base):
|
||||
__tablename__ = "training_config_resources"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
config_id: Mapped[int] = mapped_column(ForeignKey("training_configs.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
resource_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
training_level: Mapped[Optional[str]] = mapped_column(String(20), nullable=True, index=True)
|
||||
agent_guide_id: Mapped[Optional[int]] = mapped_column(ForeignKey("agent_guides.id"), nullable=True)
|
||||
kb_document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey("kb_document_versions.id"), nullable=True)
|
||||
inline_questions: Mapped[list | None] = mapped_column(JSON, nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
required_duration: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
config: Mapped[TrainingConfig] = relationship("TrainingConfig", back_populates="resources")
|
||||
agent_guide = relationship("AgentGuide", foreign_keys=[agent_guide_id])
|
||||
kb_document_version = relationship("KbDocumentVersion", foreign_keys=[kb_document_version_id])
|
||||
@@ -79,10 +79,9 @@ class User(Base):
|
||||
|
||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
training_record: Mapped[Optional['TrainingRecord']] = relationship(
|
||||
training_records: Mapped[List['TrainingRecord']] = relationship(
|
||||
'TrainingRecord',
|
||||
back_populates='user',
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
|
||||
@@ -20,10 +20,20 @@ from app.services.minio_service import minio_service
|
||||
GUIDE_USAGE_GENERAL = 'general'
|
||||
GUIDE_USAGE_TRAINING_VIDEO = 'training_video'
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf'
|
||||
GUIDE_USAGE_TRAINING_SAFETY_VIDEO = 'training_safety_video'
|
||||
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO = 'training_safety_company_video'
|
||||
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO = 'training_safety_department_video'
|
||||
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO = 'training_safety_team_video'
|
||||
GUIDE_USAGE_TRAINING_SAFETY_PDF = 'training_safety_pdf'
|
||||
ALLOWED_GUIDE_USAGES = {
|
||||
GUIDE_USAGE_GENERAL,
|
||||
GUIDE_USAGE_TRAINING_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_PDF,
|
||||
}
|
||||
|
||||
|
||||
@@ -59,14 +69,20 @@ def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str:
|
||||
归一化指南用途并校验与文件类型是否匹配。
|
||||
|
||||
用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。
|
||||
参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。
|
||||
参数约束:所有培训视频用途仅允许 video 文件;培训试题 PDF 用途仅允许 pdf 文件。
|
||||
"""
|
||||
usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL
|
||||
if usage not in ALLOWED_GUIDE_USAGES:
|
||||
raise ValidationError('Invalid guide usage')
|
||||
if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video':
|
||||
if usage in (
|
||||
GUIDE_USAGE_TRAINING_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_COMPANY_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_DEPARTMENT_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_SAFETY_TEAM_VIDEO,
|
||||
) and file_type != 'video':
|
||||
raise ValidationError('Training video usage requires a video file')
|
||||
if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf':
|
||||
if usage in (GUIDE_USAGE_TRAINING_EXAM_PDF, GUIDE_USAGE_TRAINING_SAFETY_PDF) and file_type != 'pdf':
|
||||
raise ValidationError('Training exam PDF usage requires a PDF file')
|
||||
return usage
|
||||
|
||||
|
||||
@@ -17,8 +17,9 @@ from pypdf import PdfReader
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.models import AgentGuide, KbDocumentVersion
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.kb.storage import resolve_storage_path
|
||||
from app.services.minio_service import minio_service
|
||||
from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills import loader_pdf, ocr
|
||||
@@ -443,3 +444,62 @@ def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None
|
||||
parsed['extraction_mode'] = extraction_mode
|
||||
parsed['extraction_warnings'] = ocr_warnings
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_training_question_bank_from_kb_version(version_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
从员工培训知识库当前 PDF 文档版本解析题库。
|
||||
|
||||
用途:培训配置页选择员工培训知识库试题 PDF 后,将原始文件交给现有 PDF/OCR 解析链路。
|
||||
参数约束:版本必须为当前版本、属于启用的“员工培训”知识库、未删除且扩展名为 PDF。
|
||||
Returns:
|
||||
包含题目、解析数量、跳过题号、解析模式和源文件信息的字典。
|
||||
Raises:
|
||||
NotFoundError: 文档版本不存在或原始文件不可用。
|
||||
ValidationError: 文档不符合培训试题 PDF 资源约束,或无法解析题目。
|
||||
"""
|
||||
version = db.session.get(KbDocumentVersion, version_id)
|
||||
document = version.document if version else None
|
||||
group = document.group if document else None
|
||||
if not version or not document or document.is_deleted:
|
||||
raise NotFoundError('Knowledge base document version not found')
|
||||
if not version.is_current or not group or not group.is_active or group.name != '员工培训':
|
||||
raise ValidationError('Selected document must be a current document in the employee training knowledge base')
|
||||
if str(version.source_file_ext or '').lower().lstrip('.') != 'pdf' and not str(version.source_file_name or '').lower().endswith('.pdf'):
|
||||
raise ValidationError('Selected training exam document must be a PDF')
|
||||
|
||||
source_path = resolve_storage_path(version.source_file_path)
|
||||
if not source_path or not source_path.exists():
|
||||
raise NotFoundError('Training exam PDF source file not found')
|
||||
raw_bytes = source_path.read_bytes()
|
||||
text = _extract_pdf_text(raw_bytes)
|
||||
ocr_text = ''
|
||||
ocr_warnings: list[str] = []
|
||||
extraction_mode = 'pdf_text'
|
||||
if text:
|
||||
try:
|
||||
parsed = parse_training_question_bank_text(text)
|
||||
except ValidationError as primary_error:
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text or ocr_text == text:
|
||||
raise primary_error
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr_fallback'
|
||||
else:
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text:
|
||||
raise ValidationError(
|
||||
'Training exam PDF has no readable text',
|
||||
details={'ocr_warnings': ocr_warnings},
|
||||
)
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr'
|
||||
parsed.update({
|
||||
'kb_document_version_id': version.id,
|
||||
'document_id': version.document_id,
|
||||
'source_file_name': version.source_file_name,
|
||||
'version_no': version.version_no,
|
||||
'extraction_mode': extraction_mode,
|
||||
'extraction_warnings': ocr_warnings,
|
||||
})
|
||||
return parsed
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
用途:提供培训配置 CRUD、三级资料绑定与员工培训知识库候选资料查询。
|
||||
依赖:培训、AgentGuide 与知识库 ORM 模型,以及统一业务异常。
|
||||
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, update
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import AgentGuide, KbDocument, KbDocumentVersion, KbGroup, TrainingConfig, TrainingConfigResource
|
||||
from app.services.admin.guide_service import serialize_guide
|
||||
|
||||
RESOURCE_TYPES = {"agent_guide", "kb_document_version", "inline_questions"}
|
||||
CONFIG_STATUSES = {"draft", "published", "archived"}
|
||||
TRAINING_LEVELS = {"company", "department", "team"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
TRAINING_TYPE_ALIASES = {
|
||||
"入职培训": "onboarding",
|
||||
"新人培训": "onboarding",
|
||||
"安全培训": "safety",
|
||||
}
|
||||
|
||||
|
||||
def _required_int(value: Any, field: str) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f"{field} is invalid", details={"field": field}) from exc
|
||||
if parsed <= 0:
|
||||
raise ValidationError(f"{field} is invalid", details={"field": field})
|
||||
return parsed
|
||||
|
||||
|
||||
def _resource_payload(resource: TrainingConfigResource) -> dict[str, Any]:
|
||||
data = {
|
||||
"id": resource.id,
|
||||
"resource_type": resource.resource_type,
|
||||
"training_level": resource.training_level,
|
||||
"title": resource.title,
|
||||
"required_duration": resource.required_duration,
|
||||
"sort_order": resource.sort_order,
|
||||
}
|
||||
if resource.resource_type == "agent_guide":
|
||||
data["agent_guide_id"] = resource.agent_guide_id
|
||||
data["resource"] = serialize_guide(resource.agent_guide) if resource.agent_guide else None
|
||||
elif resource.resource_type == "kb_document_version":
|
||||
data["kb_document_version_id"] = resource.kb_document_version_id
|
||||
data["resource"] = {
|
||||
"id": resource.kb_document_version.id,
|
||||
"document_id": resource.kb_document_version.document_id,
|
||||
"version_no": resource.kb_document_version.version_no,
|
||||
"source_file_name": resource.kb_document_version.source_file_name,
|
||||
"file_name": resource.kb_document_version.source_file_name,
|
||||
"file_url": f"/api/kb/document-versions/{resource.kb_document_version.id}/source-file",
|
||||
"file_type": resource.kb_document_version.source_file_ext,
|
||||
"group_name": resource.kb_document_version.document.group.name if resource.kb_document_version.document and resource.kb_document_version.document.group else None,
|
||||
} if resource.kb_document_version else None
|
||||
else:
|
||||
data["inline_questions"] = resource.inline_questions or []
|
||||
return data
|
||||
|
||||
|
||||
def serialize_training_config(config: TrainingConfig) -> dict[str, Any]:
|
||||
return {
|
||||
"id": config.id,
|
||||
"training_type": config.training_type,
|
||||
"name": config.name,
|
||||
"version": config.version,
|
||||
"status": config.status,
|
||||
"pass_score": config.pass_score,
|
||||
"settings": config.settings or {},
|
||||
"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,
|
||||
"resources": [_resource_payload(item) for item in config.resources],
|
||||
}
|
||||
|
||||
|
||||
def _validate_resource(item: dict[str, Any]) -> dict[str, Any]:
|
||||
resource_type = str(item.get("resource_type") or item.get("type") or "").strip()
|
||||
if resource_type not in RESOURCE_TYPES:
|
||||
raise ValidationError("resource_type is invalid", details={"field": "resource_type", "allowed": sorted(RESOURCE_TYPES)})
|
||||
raw_level = item.get("training_level")
|
||||
training_level = str(raw_level).strip() if raw_level is not None else None
|
||||
if training_level and training_level not in TRAINING_LEVELS:
|
||||
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)}
|
||||
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"]):
|
||||
raise NotFoundError("Agent guide not found")
|
||||
elif resource_type == "kb_document_version":
|
||||
result["kb_document_version_id"] = _required_int(item.get("kb_document_version_id"), "kb_document_version_id")
|
||||
version = db.session.get(KbDocumentVersion, result["kb_document_version_id"])
|
||||
if not version:
|
||||
raise NotFoundError("Knowledge base document version not found")
|
||||
if not version.is_current or not version.document or version.document.is_deleted or not version.document.group or not version.document.group.is_active or version.document.group.name != "员工培训":
|
||||
raise ValidationError("Only current, active documents in the employee training knowledge base can be selected")
|
||||
else:
|
||||
questions = item.get("inline_questions")
|
||||
if not isinstance(questions, list) or not questions:
|
||||
raise ValidationError("inline_questions must be a non-empty array", details={"field": "inline_questions"})
|
||||
result["inline_questions"] = questions
|
||||
return result
|
||||
|
||||
|
||||
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())
|
||||
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 name or not version:
|
||||
raise ValidationError("training_type, name and version are required")
|
||||
config.training_type, config.name, config.version = training_type, name, version
|
||||
if "pass_score" in data:
|
||||
try:
|
||||
config.pass_score = max(0, min(100, int(data["pass_score"])))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("pass_score is invalid", details={"field": "pass_score"}) from exc
|
||||
if "settings" in data:
|
||||
if not isinstance(data["settings"], dict):
|
||||
raise ValidationError("settings must be an object", details={"field": "settings"})
|
||||
config.settings = data["settings"]
|
||||
if "status" in data:
|
||||
status = str(data["status"]).strip()
|
||||
if status not in CONFIG_STATUSES:
|
||||
raise ValidationError("status is invalid", details={"field": "status", "allowed": sorted(CONFIG_STATUSES)})
|
||||
config.status = status
|
||||
config.published_at = datetime.utcnow() if status == "published" else None
|
||||
if status == "published":
|
||||
db.session.execute(
|
||||
update(TrainingConfig)
|
||||
.where(TrainingConfig.training_type == training_type, TrainingConfig.id != config.id)
|
||||
.values(status="archived")
|
||||
)
|
||||
if user_id is not None:
|
||||
config.updated_by_id = user_id
|
||||
|
||||
|
||||
def list_configs() -> list[dict[str, Any]]:
|
||||
return [serialize_training_config(item) for item in db.session.execute(select(TrainingConfig).order_by(TrainingConfig.training_type)).scalars().all()]
|
||||
|
||||
|
||||
def create_config(data: dict[str, Any], user_id: int | None) -> dict[str, Any]:
|
||||
config = TrainingConfig(training_type="", name="", version="", created_by_id=user_id, updated_by_id=user_id)
|
||||
_apply(config, data, user_id=user_id)
|
||||
config.resources = [TrainingConfigResource(**_validate_resource(item)) for item in data.get("resources", [])]
|
||||
db.session.add(config)
|
||||
db.session.commit()
|
||||
return serialize_training_config(config)
|
||||
|
||||
|
||||
def update_config(config_id: int, data: dict[str, Any], user_id: int | None) -> dict[str, Any]:
|
||||
config = db.session.get(TrainingConfig, config_id)
|
||||
if not config:
|
||||
raise NotFoundError("Training config not found")
|
||||
_apply(config, data, user_id=user_id)
|
||||
if "resources" in data:
|
||||
if not isinstance(data["resources"], list):
|
||||
raise ValidationError("resources must be an array", details={"field": "resources"})
|
||||
config.resources = [TrainingConfigResource(**_validate_resource(item)) for item in data["resources"]]
|
||||
db.session.commit()
|
||||
return serialize_training_config(config)
|
||||
|
||||
|
||||
def delete_config(config_id: int) -> None:
|
||||
config = db.session.get(TrainingConfig, config_id)
|
||||
if not config:
|
||||
raise NotFoundError("Training config not found")
|
||||
db.session.delete(config)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
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:
|
||||
return None
|
||||
config = db.session.execute(
|
||||
select(TrainingConfig)
|
||||
.where(TrainingConfig.training_type == normalized_type, TrainingConfig.status == "published")
|
||||
.order_by(TrainingConfig.published_at.desc(), TrainingConfig.id.desc())
|
||||
).scalars().first()
|
||||
return serialize_training_config(config) if config else None
|
||||
|
||||
|
||||
def list_resource_candidates() -> dict[str, list[dict[str, Any]]]:
|
||||
guides = db.session.execute(
|
||||
select(AgentGuide).where(AgentGuide.status == 1).order_by(AgentGuide.sort_order, AgentGuide.id)
|
||||
).scalars().all()
|
||||
versions = db.session.execute(
|
||||
select(KbDocumentVersion)
|
||||
.join(KbDocumentVersion.document)
|
||||
.join(KbDocument.group)
|
||||
.where(
|
||||
KbDocumentVersion.is_current.is_(True),
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbGroup.is_active.is_(True),
|
||||
KbGroup.name == "员工培训",
|
||||
)
|
||||
.order_by(KbDocumentVersion.created_at.desc(), KbDocumentVersion.id.desc())
|
||||
).scalars().all()
|
||||
return {
|
||||
"guides": [serialize_guide(item) for item in guides],
|
||||
"documents": [
|
||||
{
|
||||
"id": item.id,
|
||||
"document_id": item.document_id,
|
||||
"version_no": item.version_no,
|
||||
"file_name": item.source_file_name,
|
||||
"status": item.status,
|
||||
"group_name": item.document.group.name,
|
||||
}
|
||||
for item in versions
|
||||
],
|
||||
"training_exam_documents": [
|
||||
{
|
||||
"id": item.id,
|
||||
"document_id": item.document_id,
|
||||
"version_no": item.version_no,
|
||||
"file_name": item.source_file_name,
|
||||
"status": item.status,
|
||||
"group_name": item.document.group.name,
|
||||
}
|
||||
for item in versions
|
||||
if str(item.source_file_ext or '').lower().lstrip('.') == 'pdf' or str(item.source_file_name or '').lower().endswith('.pdf')
|
||||
],
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/training_service.py
|
||||
|
||||
用途:封装新人培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||||
用途:封装员工培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||||
依赖:app.models.TrainingRecord/User、app.extensions.db、openpyxl。
|
||||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录并提供 HR 侧聚合结果。
|
||||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录,并为安全培训补齐考试模式、三级状态和版本号的 P0 持久化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,9 +18,144 @@ from sqlalchemy import select
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import TrainingRecord, User
|
||||
from app.models import Agent, TrainingRecord, User
|
||||
from app.services.training_config_service import get_published_config
|
||||
|
||||
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
TRAINING_EXAM_MODES = {"unified", "per_level"}
|
||||
SAFETY_STAGES = {"company", "department", "team", "exam", "result"}
|
||||
SAFETY_LEVEL_KEYS = ("company", "department", "team")
|
||||
DEFAULT_PASS_SCORE = 90
|
||||
|
||||
|
||||
def _default_training_version(training_type: str) -> str:
|
||||
"""
|
||||
返回培训类型对应的默认版本号。
|
||||
|
||||
Args:
|
||||
training_type: 培训类型。当前仅允许 onboarding / safety。
|
||||
Returns:
|
||||
默认培训版本字符串。
|
||||
"""
|
||||
return "safety-v1" if training_type == "safety" else "onboarding-v1"
|
||||
|
||||
|
||||
def _normalize_training_type(value: Any) -> str:
|
||||
"""
|
||||
校验并标准化培训类型。
|
||||
|
||||
Args:
|
||||
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)})
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_training_version(value: Any, training_type: str) -> str:
|
||||
"""
|
||||
规范培训版本号,未传时按培训类型补默认值。
|
||||
|
||||
Args:
|
||||
value: 前端上传的版本号。
|
||||
training_type: 已标准化的培训类型,用于选择默认版本。
|
||||
Returns:
|
||||
培训版本号。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
return text or _default_training_version(training_type)
|
||||
|
||||
|
||||
def _normalize_exam_mode(value: Any) -> str:
|
||||
"""
|
||||
校验考试模式是否合法。
|
||||
|
||||
Args:
|
||||
value: 前端上传的考试模式,首期支持 unified / per_level。
|
||||
Returns:
|
||||
合法的考试模式。
|
||||
"""
|
||||
text = str(value or "unified").strip() or "unified"
|
||||
if text not in TRAINING_EXAM_MODES:
|
||||
raise ValidationError("exam_mode is invalid", details={"field": "exam_mode", "allowed": sorted(TRAINING_EXAM_MODES)})
|
||||
return text
|
||||
|
||||
|
||||
def _build_default_safety_progress(safety_stage: str) -> dict[str, str]:
|
||||
"""
|
||||
根据安全培训当前阶段推导三级学习进度。
|
||||
|
||||
Args:
|
||||
safety_stage: 安全培训阶段。允许 company / department / team / exam / result。
|
||||
Returns:
|
||||
company、department、team 三个级别的状态快照。
|
||||
"""
|
||||
progress: dict[str, str] = {key: "pending" for key in SAFETY_LEVEL_KEYS}
|
||||
if safety_stage == "company":
|
||||
progress["company"] = "active"
|
||||
return progress
|
||||
if safety_stage == "department":
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "active"
|
||||
return progress
|
||||
if safety_stage == "team":
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "completed"
|
||||
progress["team"] = "active"
|
||||
return progress
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "completed"
|
||||
progress["team"] = "completed"
|
||||
return progress
|
||||
|
||||
|
||||
def _normalize_safety_stage(value: Any) -> str:
|
||||
"""
|
||||
校验安全培训阶段。
|
||||
|
||||
Args:
|
||||
value: 前端上传的安全培训阶段。
|
||||
Returns:
|
||||
合法的安全培训阶段字符串。
|
||||
"""
|
||||
text = str(value or "company").strip() or "company"
|
||||
if text not in SAFETY_STAGES:
|
||||
raise ValidationError("safety_stage is invalid", details={"field": "safety_stage", "allowed": sorted(SAFETY_STAGES)})
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_safety_progress(value: Any, safety_stage: str) -> dict[str, str]:
|
||||
"""
|
||||
规范安全培训三级进度对象。
|
||||
|
||||
核心逻辑:先按当前阶段生成基准状态,再用前端已保存值做增量覆盖,确保缺字段时仍保持完整结构。
|
||||
|
||||
Args:
|
||||
value: 前端上传的三级进度对象。
|
||||
safety_stage: 当前安全培训阶段,用于补齐默认状态。
|
||||
Returns:
|
||||
标准化后的三级进度对象。
|
||||
"""
|
||||
if value in (None, ""):
|
||||
return _build_default_safety_progress(safety_stage)
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError("safety_progress must be an object", details={"field": "safety_progress"})
|
||||
normalized = _build_default_safety_progress(safety_stage)
|
||||
for key in SAFETY_LEVEL_KEYS:
|
||||
current = str(value.get(key) or "").strip()
|
||||
if current:
|
||||
normalized[key] = current
|
||||
|
||||
# 保留资源级别的进度记录
|
||||
resource_progress = value.get("resource_progress")
|
||||
if isinstance(resource_progress, dict):
|
||||
normalized["resource_progress"] = resource_progress
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _parse_iso_date(value: Any) -> Optional[date]:
|
||||
@@ -55,6 +190,158 @@ def _normalize_answer_details(value: Any) -> list[dict]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _as_record(value: Any) -> dict[str, Any]:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _normalize_pass_score(value: Any) -> int:
|
||||
parsed = int(value) if str(value or "").strip() else DEFAULT_PASS_SCORE
|
||||
return max(0, min(100, parsed))
|
||||
|
||||
|
||||
def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
规范后端训练题库结构,供服务端判卷使用。
|
||||
|
||||
Args:
|
||||
value: Agent extra_config.training_config 中的 question_bank。
|
||||
Returns:
|
||||
仅保留判卷所需字段的题库列表。
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for index, item in enumerate(value):
|
||||
raw = _as_record(item)
|
||||
prompt = str(raw.get("prompt") or "").strip()
|
||||
answer = str(raw.get("answer") or "").strip()
|
||||
question_id = str(raw.get("id") or "").strip() or f"q{index + 1}"
|
||||
if not prompt or not answer:
|
||||
continue
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
raw_options = raw.get("options")
|
||||
if isinstance(raw_options, list):
|
||||
for option_index, option in enumerate(raw_options):
|
||||
if isinstance(option, str):
|
||||
label = option.strip()
|
||||
if not label:
|
||||
continue
|
||||
options.append(
|
||||
{
|
||||
"id": str(chr(97 + option_index)),
|
||||
"label": label,
|
||||
}
|
||||
)
|
||||
continue
|
||||
option_raw = _as_record(option)
|
||||
option_id = str(option_raw.get("id") or "").strip() or str(chr(97 + option_index))
|
||||
label = str(option_raw.get("label") or "").strip()
|
||||
if option_id and label:
|
||||
options.append({"id": option_id, "label": label})
|
||||
|
||||
normalized.append(
|
||||
{
|
||||
"id": question_id,
|
||||
"type": "boolean" if str(raw.get("type") or "").strip() == "boolean" else "single",
|
||||
"prompt": prompt,
|
||||
"answer": answer,
|
||||
"options": options,
|
||||
"explanation": str(raw.get("explanation") or "").strip(),
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _resolve_training_runtime_config(agent_id: Any, training_type: str) -> tuple[int, list[dict[str, Any]]]:
|
||||
"""
|
||||
读取培训 Agent 的运行时题库配置。
|
||||
|
||||
核心逻辑:优先从 Agent.extra_config.training_config 读取正式题库和及格线,
|
||||
兼容历史顶层字段,供服务端判卷使用。
|
||||
|
||||
Args:
|
||||
agent_id: 当前培训 Agent ID。必须能定位到真实 Agent 配置。
|
||||
Returns:
|
||||
(pass_score, question_bank)
|
||||
"""
|
||||
published = get_published_config(training_type)
|
||||
if published:
|
||||
settings = _as_record(published.get("settings"))
|
||||
configured_questions = [
|
||||
question
|
||||
for resource in published.get("resources") or []
|
||||
if resource.get("resource_type") == "inline_questions"
|
||||
for question in resource.get("inline_questions") or []
|
||||
]
|
||||
questions = configured_questions or settings.get("questions") or settings.get("question_bank")
|
||||
question_bank = _normalize_question_bank(questions)
|
||||
if question_bank:
|
||||
return _normalize_pass_score(published.get("pass_score")), question_bank
|
||||
|
||||
if agent_id in (None, ""):
|
||||
return DEFAULT_PASS_SCORE, []
|
||||
|
||||
try:
|
||||
parsed_agent_id = int(agent_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("training agent is invalid", details={"field": "agent_id"}) from exc
|
||||
agent = db.session.get(Agent, parsed_agent_id)
|
||||
if not agent:
|
||||
raise ValidationError("training agent is invalid", details={"field": "agent_id"})
|
||||
|
||||
extra_config = _as_record(agent.extra_config)
|
||||
training_config = _as_record(extra_config.get("training_config"))
|
||||
merged_config = {
|
||||
**extra_config,
|
||||
**training_config,
|
||||
}
|
||||
pass_score = _normalize_pass_score(merged_config.get("pass_score") or merged_config.get("passScore") or merged_config.get("training_pass_score"))
|
||||
question_bank = _normalize_question_bank(merged_config.get("question_bank") or merged_config.get("questionBank"))
|
||||
return pass_score, question_bank
|
||||
|
||||
|
||||
def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[str, Any]], pass_score: int) -> tuple[list[dict], int, bool]:
|
||||
"""
|
||||
基于后端题库对答题记录重新判卷。
|
||||
|
||||
Args:
|
||||
answer_details: 前端上传的答题记录,仅信任 question_id / selected_option_id。
|
||||
question_bank: 后端题库真相源。
|
||||
pass_score: 当前培训及格线。
|
||||
Returns:
|
||||
(重新标记 correct 后的答案明细, 百分制分数, 是否通过)
|
||||
"""
|
||||
if not question_bank:
|
||||
raise ValidationError("training question bank is not configured", details={"field": "agent_id"})
|
||||
|
||||
question_lookup = {str(item["id"]): item for item in question_bank}
|
||||
normalized: list[dict] = []
|
||||
correct_count = 0
|
||||
for index, item in enumerate(answer_details):
|
||||
question_id = str(item.get("question_id") or item.get("questionId") or "").strip()
|
||||
selected_option_id = str(item.get("selected_option_id") or item.get("selectedOptionId") or "").strip()
|
||||
if not question_id:
|
||||
raise ValidationError("answer_details item must include question_id", details={"field": "answer_details", "index": index})
|
||||
question = question_lookup.get(question_id)
|
||||
if not question:
|
||||
raise ValidationError("answer_details question_id is invalid", details={"field": "answer_details", "index": index, "question_id": question_id})
|
||||
is_correct = selected_option_id == str(question["answer"])
|
||||
if is_correct:
|
||||
correct_count += 1
|
||||
normalized.append(
|
||||
{
|
||||
"question_id": question_id,
|
||||
"selected_option_id": selected_option_id,
|
||||
"correct": is_correct,
|
||||
}
|
||||
)
|
||||
|
||||
score = round((correct_count / len(question_bank)) * 100) if question_bank else 0
|
||||
return normalized, score, score >= pass_score
|
||||
|
||||
|
||||
def _derive_status(record: TrainingRecord) -> str:
|
||||
if bool(record.passed):
|
||||
return "passed"
|
||||
@@ -68,6 +355,11 @@ def serialize_training_record(record: TrainingRecord) -> dict[str, Any]:
|
||||
return {
|
||||
"id": record.id,
|
||||
"user_id": record.user_id,
|
||||
"training_type": record.training_type,
|
||||
"training_version": record.training_version,
|
||||
"exam_mode": record.exam_mode,
|
||||
"safety_stage": record.safety_stage,
|
||||
"safety_progress": dict(record.safety_progress or {}),
|
||||
"employee_id": record.employee_id,
|
||||
"name": record.name,
|
||||
"department": record.department,
|
||||
@@ -92,9 +384,9 @@ def _apply_user_snapshot(record: TrainingRecord, user: User) -> None:
|
||||
record.department = (user.department or "").strip() or None
|
||||
|
||||
|
||||
def get_user_training_record(user_id: int) -> Optional[TrainingRecord]:
|
||||
def get_user_training_record(user_id: int, training_type: str = "onboarding") -> Optional[TrainingRecord]:
|
||||
"""查询指定用户当前培训记录。"""
|
||||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id)
|
||||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id, TrainingRecord.training_type == training_type)
|
||||
return db.session.execute(stmt).scalar_one_or_none()
|
||||
|
||||
|
||||
@@ -108,6 +400,13 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
Returns:
|
||||
已保存的 TrainingRecord。
|
||||
"""
|
||||
training_type = _normalize_training_type(payload.get("training_type") or payload.get("type") or "onboarding")
|
||||
agent_id = payload.get("agent_id") or payload.get("agentId")
|
||||
training_version = _normalize_training_version(
|
||||
payload.get("training_version") or payload.get("trainingVersion"),
|
||||
training_type,
|
||||
)
|
||||
exam_mode = _normalize_exam_mode(payload.get("exam_mode") or payload.get("examMode") or "unified")
|
||||
stage = str(payload.get("stage") or "video").strip() or "video"
|
||||
if stage not in TRAINING_STAGES:
|
||||
raise ValidationError("stage is invalid", details={"field": "stage", "allowed": sorted(TRAINING_STAGES)})
|
||||
@@ -123,13 +422,35 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
raise ValidationError("attempt_count must be >= 0", details={"field": "attempt_count"})
|
||||
|
||||
answer_details = _normalize_answer_details(payload.get("answer_details") or payload.get("answerDetails"))
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= 90)
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
pass_score, question_bank = _resolve_training_runtime_config(agent_id, training_type)
|
||||
if agent_id not in (None, "") and answer_details and not question_bank:
|
||||
raise ValidationError("training question bank is not configured", details={"field": "agent_id"})
|
||||
if question_bank and answer_details:
|
||||
answer_details, score, passed = _grade_answer_details(answer_details, question_bank, pass_score)
|
||||
else:
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= pass_score)
|
||||
|
||||
record = get_user_training_record(user.id)
|
||||
if stage == "result" and question_bank and not answer_details:
|
||||
raise ValidationError("answer_details is required when submitting result", details={"field": "answer_details"})
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
safety_stage = None
|
||||
safety_progress = None
|
||||
if training_type == "safety":
|
||||
safety_stage = _normalize_safety_stage(payload.get("safety_stage") or payload.get("safetyStage") or "company")
|
||||
safety_progress = _normalize_safety_progress(
|
||||
payload.get("safety_progress") or payload.get("safetyProgress"),
|
||||
safety_stage,
|
||||
)
|
||||
|
||||
record = get_user_training_record(user.id, training_type)
|
||||
if not record:
|
||||
record = TrainingRecord(
|
||||
user_id=user.id,
|
||||
training_type=training_type,
|
||||
training_version=training_version,
|
||||
exam_mode=exam_mode,
|
||||
safety_stage=safety_stage,
|
||||
safety_progress=safety_progress,
|
||||
join_date=join_date or date.today(),
|
||||
started_at=datetime.utcnow(),
|
||||
)
|
||||
@@ -138,6 +459,10 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
record.join_date = join_date
|
||||
|
||||
_apply_user_snapshot(record, user)
|
||||
record.training_version = training_version
|
||||
record.exam_mode = exam_mode
|
||||
record.safety_stage = safety_stage
|
||||
record.safety_progress = safety_progress
|
||||
record.stage = stage
|
||||
record.current_question_index = current_question_index
|
||||
record.score = score
|
||||
@@ -164,7 +489,13 @@ class TrainingListResult:
|
||||
total: int
|
||||
|
||||
|
||||
def list_training_records(*, keyword: str | None = None, department: str | None = None, status: str | None = None) -> TrainingListResult:
|
||||
def list_training_records(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
department: str | None = None,
|
||||
status: str | None = None,
|
||||
training_type: str | None = None,
|
||||
) -> TrainingListResult:
|
||||
"""按筛选条件列出培训记录。"""
|
||||
query = db.session.query(TrainingRecord).order_by(TrainingRecord.updated_at.desc(), TrainingRecord.id.desc())
|
||||
records = query.all()
|
||||
@@ -172,6 +503,7 @@ def list_training_records(*, keyword: str | None = None, department: str | None
|
||||
keyword_text = str(keyword or "").strip().lower()
|
||||
department_text = str(department or "").strip()
|
||||
status_text = str(status or "").strip()
|
||||
type_text = str(training_type or "").strip()
|
||||
|
||||
filtered: list[TrainingRecord] = []
|
||||
for record in records:
|
||||
@@ -189,6 +521,8 @@ def list_training_records(*, keyword: str | None = None, department: str | None
|
||||
continue
|
||||
if status_text and status_text != "all" and record_status != status_text:
|
||||
continue
|
||||
if type_text and type_text != "all" and record.training_type != type_text:
|
||||
continue
|
||||
filtered.append(record)
|
||||
|
||||
return TrainingListResult(records=filtered, total=len(filtered))
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
from app import create_app
|
||||
from app.extensions import db
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
try:
|
||||
db.session.execute(db.text('''DROP INDEX IF EXISTS ix_training_records_user_id;'''))
|
||||
db.session.execute(db.text('''ALTER TABLE training_records DROP CONSTRAINT IF EXISTS uq_training_records_user_id;'''))
|
||||
db.session.commit()
|
||||
print("Legacy unique constraint on user_id dropped.")
|
||||
except Exception as e:
|
||||
print("Error dropping legacy unique constraint/index:", e)
|
||||
db.session.rollback()
|
||||
|
||||
try:
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD COLUMN IF NOT EXISTS training_version VARCHAR(64) NOT NULL DEFAULT 'onboarding-v1';'''))
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD COLUMN IF NOT EXISTS exam_mode VARCHAR(20) NOT NULL DEFAULT 'unified';'''))
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD COLUMN IF NOT EXISTS safety_stage VARCHAR(20);'''))
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD COLUMN IF NOT EXISTS safety_progress JSONB;'''))
|
||||
db.session.execute(db.text('''CREATE INDEX IF NOT EXISTS ix_training_records_training_version ON training_records (training_version);'''))
|
||||
db.session.execute(db.text('''CREATE INDEX IF NOT EXISTS ix_training_records_safety_stage ON training_records (safety_stage);'''))
|
||||
db.session.commit()
|
||||
print("Runtime columns and indexes added.")
|
||||
except Exception as e:
|
||||
print("Error adding runtime columns/indexes:", e)
|
||||
db.session.rollback()
|
||||
|
||||
try:
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD COLUMN IF NOT EXISTS training_type VARCHAR(50) NOT NULL DEFAULT 'onboarding';'''))
|
||||
db.session.execute(db.text('''CREATE INDEX IF NOT EXISTS ix_training_records_training_type ON training_records (training_type);'''))
|
||||
db.session.commit()
|
||||
print("Column and index added.")
|
||||
except Exception as e:
|
||||
print("Error adding column/index:", e)
|
||||
db.session.rollback()
|
||||
|
||||
try:
|
||||
db.session.execute(db.text('''ALTER TABLE training_records ADD CONSTRAINT uq_user_training_type UNIQUE (user_id, training_type);'''))
|
||||
db.session.commit()
|
||||
print("Constraint added.")
|
||||
except Exception as e:
|
||||
print("Constraint likely exists:", e)
|
||||
db.session.rollback()
|
||||
|
||||
try:
|
||||
db.session.execute(db.text('''ALTER TABLE schedule_tasks ADD COLUMN IF NOT EXISTS job_params JSONB;'''))
|
||||
db.session.commit()
|
||||
print("job_params column added to schedule_tasks.")
|
||||
except Exception as e:
|
||||
print("Error adding job_params to schedule_tasks:", e)
|
||||
db.session.rollback()
|
||||
@@ -0,0 +1,28 @@
|
||||
"""add_training_type
|
||||
|
||||
Revision ID: 3d65de4125ed
|
||||
Revises: e5f7a9b1c3d4
|
||||
Create Date: 2026-08-04 18:23:04.203981
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '3d65de4125ed'
|
||||
down_revision = 'e5f7a9b1c3d4'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('training_records', sa.Column('training_type', sa.String(length=50), nullable=False, server_default='onboarding'))
|
||||
op.create_index(op.f('ix_training_records_training_type'), 'training_records', ['training_type'], unique=False)
|
||||
op.create_unique_constraint('uq_user_training_type', 'training_records', ['user_id', 'training_type'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint('uq_user_training_type', 'training_records', type_='unique')
|
||||
op.drop_index(op.f('ix_training_records_training_type'), table_name='training_records')
|
||||
op.drop_column('training_records', 'training_type')
|
||||
@@ -0,0 +1,25 @@
|
||||
"""drop_training_user_unique
|
||||
|
||||
Revision ID: 4f92c6b1a3de
|
||||
Revises: 8b71d2e4a9c1
|
||||
Create Date: 2026-08-06 19:05:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '4f92c6b1a3de'
|
||||
down_revision = '8b71d2e4a9c1'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.execute("DROP INDEX IF EXISTS ix_training_records_user_id;")
|
||||
op.execute("ALTER TABLE training_records DROP CONSTRAINT IF EXISTS uq_training_records_user_id;")
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute("ALTER TABLE training_records ADD CONSTRAINT uq_training_records_user_id UNIQUE (user_id);")
|
||||
op.execute("CREATE UNIQUE INDEX IF NOT EXISTS ix_training_records_user_id ON training_records (user_id);")
|
||||
@@ -0,0 +1,24 @@
|
||||
"""merge multiple heads
|
||||
|
||||
Revision ID: 69f452bb049f
|
||||
Revises: 4f92c6b1a3de, a0b1c2d3e4f5
|
||||
Create Date: 2026-08-07 12:05:26.063430
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '69f452bb049f'
|
||||
down_revision = ('4f92c6b1a3de', 'a0b1c2d3e4f5')
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
pass
|
||||
|
||||
|
||||
def downgrade():
|
||||
pass
|
||||
@@ -0,0 +1,56 @@
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "7a8b9c0d1e2f"
|
||||
down_revision = "69f452bb049f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
"training_configs",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("training_type", sa.String(length=50), nullable=False),
|
||||
sa.Column("name", sa.String(length=100), nullable=False),
|
||||
sa.Column("version", sa.String(length=64), nullable=False),
|
||||
sa.Column("status", sa.String(length=20), nullable=False),
|
||||
sa.Column("pass_score", sa.Integer(), nullable=False),
|
||||
sa.Column("settings", sa.JSON(), nullable=True),
|
||||
sa.Column("created_by_id", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_by_id", sa.Integer(), nullable=True),
|
||||
sa.Column("published_at", sa.DateTime(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["created_by_id"], ["users.id"]),
|
||||
sa.ForeignKeyConstraint(["updated_by_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index("ix_training_configs_training_type", "training_configs", ["training_type"], unique=False)
|
||||
op.create_index("ix_training_configs_status", "training_configs", ["status"], unique=False)
|
||||
op.create_table(
|
||||
"training_config_resources",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("config_id", sa.Integer(), nullable=False),
|
||||
sa.Column("resource_type", sa.String(length=32), nullable=False),
|
||||
sa.Column("agent_guide_id", sa.Integer(), nullable=True),
|
||||
sa.Column("kb_document_version_id", sa.Integer(), nullable=True),
|
||||
sa.Column("inline_questions", sa.JSON(), nullable=True),
|
||||
sa.Column("title", sa.String(length=255), nullable=True),
|
||||
sa.Column("sort_order", sa.Integer(), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(["agent_guide_id"], ["agent_guides.id"]),
|
||||
sa.ForeignKeyConstraint(["config_id"], ["training_configs.id"], ondelete="CASCADE"),
|
||||
sa.ForeignKeyConstraint(["kb_document_version_id"], ["kb_document_versions.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index("ix_training_config_resources_config_id", "training_config_resources", ["config_id"], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_training_config_resources_config_id", table_name="training_config_resources")
|
||||
op.drop_table("training_config_resources")
|
||||
op.drop_index("ix_training_configs_status", table_name="training_configs")
|
||||
op.drop_index("ix_training_configs_training_type", table_name="training_configs")
|
||||
op.drop_table("training_configs")
|
||||
@@ -0,0 +1,56 @@
|
||||
"""add training runtime fields
|
||||
|
||||
Revision ID: 8b71d2e4a9c1
|
||||
Revises: 3d65de4125ed
|
||||
Create Date: 2026-08-06 16:20:00.000000
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "8b71d2e4a9c1"
|
||||
down_revision = "3d65de4125ed"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"training_records",
|
||||
sa.Column("training_version", sa.String(length=64), nullable=False, server_default="onboarding-v1"),
|
||||
)
|
||||
op.add_column(
|
||||
"training_records",
|
||||
sa.Column("exam_mode", sa.String(length=20), nullable=False, server_default="unified"),
|
||||
)
|
||||
op.add_column(
|
||||
"training_records",
|
||||
sa.Column("safety_stage", sa.String(length=20), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"training_records",
|
||||
sa.Column("safety_progress", sa.JSON(), nullable=True),
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_training_records_training_version"),
|
||||
"training_records",
|
||||
["training_version"],
|
||||
unique=False,
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_training_records_safety_stage"),
|
||||
"training_records",
|
||||
["safety_stage"],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f("ix_training_records_safety_stage"), table_name="training_records")
|
||||
op.drop_index(op.f("ix_training_records_training_version"), table_name="training_records")
|
||||
op.drop_column("training_records", "safety_progress")
|
||||
op.drop_column("training_records", "safety_stage")
|
||||
op.drop_column("training_records", "exam_mode")
|
||||
op.drop_column("training_records", "training_version")
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
"""
|
||||
backend/migrations/versions/b6c8d0e2f4a6_migrate_legacy_onboarding_training_config.py
|
||||
|
||||
用途:把员工培训 Agent 的旧版 extra_config.training_config 搬迁为 onboarding 培训配置。
|
||||
依赖:agents、agent_guides、training_configs、training_config_resources 表及 SQLAlchemy JSON 类型。
|
||||
逻辑:仅在 onboarding 尚不存在时选择最匹配的旧 Agent,复制结构化内容并关联其启用的入职视频与试题 PDF;降级不删除业务数据。
|
||||
|
||||
Revision ID: b6c8d0e2f4a6
|
||||
Revises: 7a8b9c0d1e2f
|
||||
Create Date: 2026-08-10 00:00:00.000000
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "b6c8d0e2f4a6"
|
||||
down_revision = "7a8b9c0d1e2f"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
ONBOARDING_TYPE = "onboarding"
|
||||
ONBOARDING_VERSION = "onboarding-v1"
|
||||
ONBOARDING_NAME = "入职培训"
|
||||
CONTENT_KEYS = (
|
||||
"summary_points",
|
||||
"summary_checklist",
|
||||
"employee_chat_suggested_questions",
|
||||
"hr_chat_suggested_questions",
|
||||
"question_bank",
|
||||
)
|
||||
|
||||
|
||||
def _as_dict(value: Any) -> dict[str, Any]:
|
||||
"""
|
||||
将数据库 JSON 值规范为字典,隔离历史空值或异常结构。
|
||||
|
||||
Args:
|
||||
value: SQLAlchemy 从 agents.extra_config 读取的 JSON 值。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 字典原值;非字典统一返回空字典。
|
||||
"""
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _has_meaningful_value(value: Any) -> bool:
|
||||
"""
|
||||
判断旧培训字段是否包含可供员工端使用的实质内容。
|
||||
|
||||
Args:
|
||||
value: 摘要、建议问题或题库等任意 JSON 值;空白字符串和空容器不算内容。
|
||||
|
||||
Returns:
|
||||
bool: 存在非空文本、非空容器或其它有效标量时返回 True。
|
||||
"""
|
||||
if value is None or value is False:
|
||||
return False
|
||||
if isinstance(value, str):
|
||||
return bool(value.strip())
|
||||
if isinstance(value, (list, tuple, set, dict)):
|
||||
return bool(value)
|
||||
return True
|
||||
|
||||
|
||||
def _legacy_training_config(extra_config: Any) -> dict[str, Any]:
|
||||
"""
|
||||
从 Agent extra_config 中读取旧版培训配置。
|
||||
|
||||
Args:
|
||||
extra_config: agents.extra_config JSON 值。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: training_config 字典;缺失或结构异常时返回空字典。
|
||||
"""
|
||||
return _as_dict(_as_dict(extra_config).get("training_config"))
|
||||
|
||||
|
||||
def _agent_rank(agent: sa.RowMapping) -> tuple[int, int, int, int]:
|
||||
"""
|
||||
对包含旧培训配置的 Agent 排序,优先选择启用的入职/员工培训应用。
|
||||
|
||||
Args:
|
||||
agent: 含 id、name、is_active、extra_config 的数据库行映射。
|
||||
|
||||
Returns:
|
||||
tuple[int, int, int, int]: 可降序比较的匹配分;最后以较小主键稳定决策。
|
||||
"""
|
||||
extra = _as_dict(agent["extra_config"])
|
||||
name = str(agent["name"] or "").replace(" ", "")
|
||||
onboarding_name = int("入职" in name or "员工培训" in name)
|
||||
non_safety_name = int("安全" not in name)
|
||||
workspace_enabled = int(extra.get("training_workspace_enabled") in (True, "true", "True", 1))
|
||||
active = int(bool(agent["is_active"]))
|
||||
return onboarding_name, non_safety_name, workspace_enabled + active, -int(agent["id"])
|
||||
|
||||
|
||||
def _select_legacy_agent(connection: sa.Connection, agents: sa.Table) -> sa.RowMapping | None:
|
||||
"""
|
||||
选择承载员工培训旧配置的 Agent,不依赖 PostgreSQL 专属 JSON 查询语法。
|
||||
|
||||
Args:
|
||||
connection: Alembic 当前事务连接。
|
||||
agents: 迁移内声明的 agents 轻量表对象。
|
||||
|
||||
Returns:
|
||||
RowMapping | None: 最匹配且含 training_config 的 Agent;没有候选时返回 None。
|
||||
"""
|
||||
rows = connection.execute(
|
||||
sa.select(agents.c.id, agents.c.name, agents.c.is_active, agents.c.extra_config)
|
||||
).mappings().all()
|
||||
candidates = [row for row in rows if _legacy_training_config(row["extra_config"])]
|
||||
return max(candidates, key=_agent_rank) if candidates else None
|
||||
|
||||
|
||||
def _normalize_pass_score(value: Any) -> int:
|
||||
"""
|
||||
将旧及格线约束到百分制范围,异常值回退为 90。
|
||||
|
||||
Args:
|
||||
value: training_config.pass_score 旧值。
|
||||
|
||||
Returns:
|
||||
int: 0 至 100 之间的整数。
|
||||
"""
|
||||
try:
|
||||
return max(0, min(100, int(value)))
|
||||
except (TypeError, ValueError):
|
||||
return 90
|
||||
|
||||
|
||||
def _build_settings(legacy_config: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
复制培训复盘和员工/HR 建议问题到新配置 settings。
|
||||
|
||||
Args:
|
||||
legacy_config: 旧 extra_config.training_config 字典。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 保留原 JSON 结构的四类员工端配置。
|
||||
"""
|
||||
return {
|
||||
key: legacy_config[key]
|
||||
for key in CONTENT_KEYS
|
||||
if key != "question_bank" and key in legacy_config
|
||||
}
|
||||
|
||||
|
||||
def _insert_guide_resources(
|
||||
connection: sa.Connection,
|
||||
guides: sa.Table,
|
||||
resources: sa.Table,
|
||||
*,
|
||||
agent_id: int,
|
||||
config_id: int,
|
||||
now: datetime,
|
||||
) -> None:
|
||||
"""
|
||||
关联所选 Agent 已启用的入职视频与培训试题 PDF 指南。
|
||||
|
||||
Args:
|
||||
connection: Alembic 当前事务连接。
|
||||
guides: agent_guides 轻量表对象。
|
||||
resources: training_config_resources 轻量表对象。
|
||||
agent_id: 被选中员工培训 Agent 主键。
|
||||
config_id: 新建 onboarding 配置主键。
|
||||
now: 本次迁移统一使用的 UTC 时间。
|
||||
|
||||
Returns:
|
||||
None: 资源直接写入当前迁移事务。
|
||||
"""
|
||||
guide_rows = connection.execute(
|
||||
sa.select(guides.c.id, guides.c.file_name, guides.c.guide_usage, guides.c.sort_order)
|
||||
.where(
|
||||
guides.c.agent_id == agent_id,
|
||||
guides.c.status == 1,
|
||||
sa.or_(
|
||||
sa.and_(guides.c.guide_usage == "training_video", guides.c.file_type == "video"),
|
||||
sa.and_(guides.c.guide_usage == "training_exam_pdf", guides.c.file_type == "pdf"),
|
||||
),
|
||||
)
|
||||
.order_by(guides.c.sort_order.asc(), guides.c.id.asc())
|
||||
).mappings().all()
|
||||
for index, guide in enumerate(guide_rows):
|
||||
connection.execute(
|
||||
resources.insert().values(
|
||||
config_id=config_id,
|
||||
resource_type="agent_guide",
|
||||
agent_guide_id=guide["id"],
|
||||
title=guide["file_name"],
|
||||
sort_order=index,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""
|
||||
幂等创建 onboarding-v1,并从员工培训 Agent 搬迁旧配置与启用资料。
|
||||
|
||||
核心逻辑:已有任意 onboarding 配置立即跳过;否则选择旧 Agent,复制配置,
|
||||
有摘要、建议问题或题库时发布,没有实质内容时保留草稿状态。
|
||||
|
||||
Returns:
|
||||
None: 数据变更由 Alembic 当前事务提交。
|
||||
"""
|
||||
metadata = sa.MetaData()
|
||||
agents = sa.Table(
|
||||
"agents",
|
||||
metadata,
|
||||
sa.Column("id", sa.Integer),
|
||||
sa.Column("name", sa.String),
|
||||
sa.Column("extra_config", sa.JSON),
|
||||
sa.Column("is_active", sa.Boolean),
|
||||
)
|
||||
guides = sa.Table(
|
||||
"agent_guides",
|
||||
metadata,
|
||||
sa.Column("id", sa.Integer),
|
||||
sa.Column("agent_id", sa.Integer),
|
||||
sa.Column("file_name", sa.String),
|
||||
sa.Column("file_type", sa.String),
|
||||
sa.Column("guide_usage", sa.String),
|
||||
sa.Column("sort_order", sa.Integer),
|
||||
sa.Column("status", sa.Integer),
|
||||
)
|
||||
configs = sa.Table(
|
||||
"training_configs",
|
||||
metadata,
|
||||
sa.Column("id", sa.Integer, primary_key=True),
|
||||
sa.Column("training_type", sa.String),
|
||||
sa.Column("name", sa.String),
|
||||
sa.Column("version", sa.String),
|
||||
sa.Column("status", sa.String),
|
||||
sa.Column("pass_score", sa.Integer),
|
||||
sa.Column("settings", sa.JSON),
|
||||
sa.Column("published_at", sa.DateTime),
|
||||
sa.Column("created_at", sa.DateTime),
|
||||
sa.Column("updated_at", sa.DateTime),
|
||||
)
|
||||
resources = sa.Table(
|
||||
"training_config_resources",
|
||||
metadata,
|
||||
sa.Column("config_id", sa.Integer),
|
||||
sa.Column("resource_type", sa.String),
|
||||
sa.Column("agent_guide_id", sa.Integer),
|
||||
sa.Column("inline_questions", sa.JSON),
|
||||
sa.Column("title", sa.String),
|
||||
sa.Column("sort_order", sa.Integer),
|
||||
sa.Column("created_at", sa.DateTime),
|
||||
sa.Column("updated_at", sa.DateTime),
|
||||
)
|
||||
connection = op.get_bind()
|
||||
|
||||
existing_id = connection.scalar(
|
||||
sa.select(configs.c.id).where(configs.c.training_type == ONBOARDING_TYPE).limit(1)
|
||||
)
|
||||
if existing_id is not None:
|
||||
return
|
||||
|
||||
agent = _select_legacy_agent(connection, agents)
|
||||
legacy_config = _legacy_training_config(agent["extra_config"]) if agent is not None else {}
|
||||
has_content = any(_has_meaningful_value(legacy_config.get(key)) for key in CONTENT_KEYS)
|
||||
now = datetime.utcnow()
|
||||
config_id = connection.execute(
|
||||
configs.insert()
|
||||
.values(
|
||||
training_type=ONBOARDING_TYPE,
|
||||
name=ONBOARDING_NAME,
|
||||
version=ONBOARDING_VERSION,
|
||||
status="published" if has_content else "draft",
|
||||
pass_score=_normalize_pass_score(legacy_config.get("pass_score")),
|
||||
settings=_build_settings(legacy_config),
|
||||
published_at=now if has_content else None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
.returning(configs.c.id)
|
||||
).scalar_one()
|
||||
|
||||
if agent is not None:
|
||||
_insert_guide_resources(
|
||||
connection,
|
||||
guides,
|
||||
resources,
|
||||
agent_id=int(agent["id"]),
|
||||
config_id=int(config_id),
|
||||
now=now,
|
||||
)
|
||||
question_bank = legacy_config.get("question_bank")
|
||||
if _has_meaningful_value(question_bank):
|
||||
connection.execute(
|
||||
resources.insert().values(
|
||||
config_id=config_id,
|
||||
resource_type="inline_questions",
|
||||
inline_questions=question_bank,
|
||||
title="入职培训题库",
|
||||
sort_order=1000,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""
|
||||
保留已搬迁或后续人工维护的 onboarding 业务数据。
|
||||
|
||||
Returns:
|
||||
None: 数据迁移不可安全区分自动创建和同名人工配置,因此不执行删除。
|
||||
"""
|
||||
return None
|
||||
@@ -0,0 +1,25 @@
|
||||
"""add required_duration to training_config_resources
|
||||
|
||||
Revision ID: b786eb92538e
|
||||
Revises: c1e2f3a4b5c6
|
||||
Create Date: 2026-08-11 17:03:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'b786eb92538e'
|
||||
down_revision = 'c1e2f3a4b5c6'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table('training_config_resources', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('required_duration', sa.Integer(), nullable=False, server_default='0'))
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('training_config_resources', schema=None) as batch_op:
|
||||
batch_op.drop_column('required_duration')
|
||||
@@ -0,0 +1,38 @@
|
||||
"""新增培训资料级别字段。"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "c1e2f3a4b5c6"
|
||||
down_revision = "b6c8d0e2f4a6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("training_config_resources", sa.Column("training_level", sa.String(length=20), nullable=True))
|
||||
op.create_index("ix_training_config_resources_training_level", "training_config_resources", ["training_level"])
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE training_config_resources AS resource
|
||||
SET training_level = CASE guide.guide_usage
|
||||
WHEN 'training_safety_department_video' THEN 'department'
|
||||
WHEN 'training_safety_team_video' THEN 'team'
|
||||
ELSE 'company'
|
||||
END
|
||||
FROM agent_guides AS guide
|
||||
WHERE resource.agent_guide_id = guide.id
|
||||
AND resource.resource_type = 'agent_guide'
|
||||
AND resource.training_level IS NULL
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
"UPDATE training_config_resources SET training_level = 'company' "
|
||||
"WHERE resource_type = 'kb_document_version' AND training_level IS NULL"
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_training_config_resources_training_level", table_name="training_config_resources")
|
||||
op.drop_column("training_config_resources", "training_level")
|
||||
+3
-1
@@ -3,6 +3,8 @@
|
||||
backend/run.py
|
||||
开发环境启动脚本
|
||||
"""
|
||||
import os
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User, Agent
|
||||
|
||||
@@ -15,4 +17,4 @@ def make_shell_context():
|
||||
if __name__ == '__main__':
|
||||
# MacOS ControlCenter uses port 5000, so we use 5052
|
||||
# (原5002易被Trae IDE自动端口转发劫持)
|
||||
app.run(host='0.0.0.0', port=5052)
|
||||
app.run(host='0.0.0.0', port=int(os.getenv('HXOPS_BACKEND_PORT', '5052')))
|
||||
@@ -14,7 +14,7 @@ from io import BytesIO
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import TrainingRecord, User
|
||||
from app.models import Agent, TrainingRecord, User
|
||||
|
||||
|
||||
def _create_user(
|
||||
@@ -43,6 +43,65 @@ def _create_user(
|
||||
return user
|
||||
|
||||
|
||||
def _create_training_agent(*, name: str = "training_agent") -> Agent:
|
||||
"""创建带正式题库配置的培训 Agent,供服务端判卷测试使用。"""
|
||||
agent = Agent(
|
||||
name=name,
|
||||
description="training agent",
|
||||
type="api",
|
||||
agent_code="training",
|
||||
runtime_provider="dify",
|
||||
conversation_mode="chat",
|
||||
dify_app_type="chatflow",
|
||||
handler_config={"content_profile": "training"},
|
||||
extra_config={
|
||||
"training_workspace_enabled": True,
|
||||
"training_config": {
|
||||
"pass_score": 90,
|
||||
"question_bank": [
|
||||
{
|
||||
"id": "q1",
|
||||
"type": "single",
|
||||
"prompt": "题目1",
|
||||
"answer": "A",
|
||||
"options": [
|
||||
{"id": "A", "label": "A. 正确答案"},
|
||||
{"id": "B", "label": "B. 干扰项"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "q2",
|
||||
"type": "single",
|
||||
"prompt": "题目2",
|
||||
"answer": "B",
|
||||
"options": [
|
||||
{"id": "A", "label": "A. 干扰项"},
|
||||
{"id": "B", "label": "B. 正确答案"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"id": "q3",
|
||||
"type": "single",
|
||||
"prompt": "题目3",
|
||||
"answer": "C",
|
||||
"options": [
|
||||
{"id": "A", "label": "A. 干扰项"},
|
||||
{"id": "B", "label": "B. 干扰项"},
|
||||
{"id": "C", "label": "C. 正确答案"},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
db.session.expunge(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _json_error(response) -> dict:
|
||||
"""提取统一错误 envelope,便于断言错误码与详情。"""
|
||||
body = response.get_json()
|
||||
@@ -65,6 +124,7 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
"""员工侧培训进度应支持空记录读取、过程保存、结果结算与再次读取回显。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="trainee_roundtrip")
|
||||
agent = _create_training_agent(name="roundtrip_agent")
|
||||
|
||||
headers = _auth_headers(user)
|
||||
|
||||
@@ -73,6 +133,7 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
assert empty_res.get_json() is None
|
||||
|
||||
process_payload = {
|
||||
"agent_id": agent.id,
|
||||
"stage": "exam",
|
||||
"current_question_index": 3,
|
||||
"score": 15,
|
||||
@@ -82,15 +143,18 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
"answer_details": [
|
||||
{"question_id": "q1", "selected_option_id": "A", "correct": True},
|
||||
{"question_id": "q2", "selected_option_id": "B", "correct": False},
|
||||
{"question_id": "q3", "selected_option_id": "C", "correct": True},
|
||||
{"question_id": "q3", "selected_option_id": "A", "correct": True},
|
||||
],
|
||||
}
|
||||
save_process_res = client.put("/api/user/training-record/progress", headers=headers, json=process_payload)
|
||||
assert save_process_res.status_code == 200
|
||||
process_body = save_process_res.get_json()
|
||||
assert process_body["stage"] == "exam"
|
||||
assert process_body["training_type"] == "onboarding"
|
||||
assert process_body["training_version"] == "onboarding-v1"
|
||||
assert process_body["exam_mode"] == "unified"
|
||||
assert process_body["current_question_index"] == 3
|
||||
assert process_body["score"] == 15
|
||||
assert process_body["score"] == 67
|
||||
assert process_body["passed"] is False
|
||||
assert process_body["status"] == "in_progress"
|
||||
assert process_body["employee_id"] == user.employee_id
|
||||
@@ -102,19 +166,24 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
assert read_back_res.get_json()["current_question_index"] == 3
|
||||
|
||||
result_payload = {
|
||||
"agent_id": agent.id,
|
||||
"stage": "result",
|
||||
"current_question_index": 20,
|
||||
"score": 95,
|
||||
"passed": False,
|
||||
"attempt_count": 2,
|
||||
"join_date": "2026-07-04",
|
||||
"answer_details": process_payload["answer_details"],
|
||||
"answer_details": [
|
||||
{"question_id": "q1", "selected_option_id": "A", "correct": False},
|
||||
{"question_id": "q2", "selected_option_id": "B", "correct": False},
|
||||
{"question_id": "q3", "selected_option_id": "C", "correct": False},
|
||||
],
|
||||
}
|
||||
save_result_res = client.put("/api/user/training-record/progress", headers=headers, json=result_payload)
|
||||
assert save_result_res.status_code == 200
|
||||
result_body = save_result_res.get_json()
|
||||
assert result_body["stage"] == "result"
|
||||
assert result_body["score"] == 95
|
||||
assert result_body["score"] == 100
|
||||
assert result_body["passed"] is True
|
||||
assert result_body["status"] == "passed"
|
||||
assert isinstance(result_body["completion_time"], str) and result_body["completion_time"]
|
||||
@@ -122,13 +191,110 @@ def test_training_user_progress_round_trip_and_completion(client, app):
|
||||
with app.app_context():
|
||||
record = db.session.query(TrainingRecord).filter_by(user_id=user.id).one()
|
||||
assert record.stage == "result"
|
||||
assert record.score == 95
|
||||
assert record.training_type == "onboarding"
|
||||
assert record.training_version == "onboarding-v1"
|
||||
assert record.exam_mode == "unified"
|
||||
assert record.score == 100
|
||||
assert record.passed is True
|
||||
assert record.attempt_count == 2
|
||||
assert record.join_date == date(2026, 7, 4)
|
||||
assert record.completion_time is not None
|
||||
|
||||
|
||||
def test_safety_training_progress_round_trip(client, app):
|
||||
"""安全培训应持久化培训版本、考试模式、三级状态和级别进度。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="safety_roundtrip")
|
||||
agent = _create_training_agent(name="safety_agent")
|
||||
|
||||
headers = _auth_headers(user)
|
||||
progress_payload = {
|
||||
"agent_id": agent.id,
|
||||
"type": "safety",
|
||||
"training_version": "safety-v1",
|
||||
"exam_mode": "unified",
|
||||
"safety_stage": "team",
|
||||
"safety_progress": {
|
||||
"company": "completed",
|
||||
"department": "completed",
|
||||
"team": "active",
|
||||
},
|
||||
"stage": "summary",
|
||||
"current_question_index": 0,
|
||||
"score": 0,
|
||||
"passed": False,
|
||||
"attempt_count": 0,
|
||||
"join_date": "2026-08-06",
|
||||
"answer_details": [],
|
||||
}
|
||||
|
||||
save_res = client.put("/api/user/training-record/progress", headers=headers, json=progress_payload)
|
||||
assert save_res.status_code == 200
|
||||
save_body = save_res.get_json()
|
||||
assert save_body["training_type"] == "safety"
|
||||
assert save_body["training_version"] == "safety-v1"
|
||||
assert save_body["exam_mode"] == "unified"
|
||||
assert save_body["safety_stage"] == "team"
|
||||
assert save_body["safety_progress"] == {
|
||||
"company": "completed",
|
||||
"department": "completed",
|
||||
"team": "active",
|
||||
}
|
||||
|
||||
read_res = client.get("/api/user/training-record?type=safety", headers=headers)
|
||||
assert read_res.status_code == 200
|
||||
read_body = read_res.get_json()
|
||||
assert read_body["training_type"] == "safety"
|
||||
assert read_body["safety_stage"] == "team"
|
||||
assert read_body["safety_progress"]["department"] == "completed"
|
||||
|
||||
with app.app_context():
|
||||
record = db.session.query(TrainingRecord).filter_by(user_id=user.id, training_type="safety").one()
|
||||
assert record.training_version == "safety-v1"
|
||||
assert record.exam_mode == "unified"
|
||||
assert record.safety_stage == "team"
|
||||
assert record.safety_progress == {
|
||||
"company": "completed",
|
||||
"department": "completed",
|
||||
"team": "active",
|
||||
}
|
||||
|
||||
|
||||
def test_training_result_is_graded_by_server_question_bank(client, app):
|
||||
"""服务端应基于 Agent 题库重算分数与通过状态,不能信任前端伪造结果。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="graded_by_server")
|
||||
agent = _create_training_agent(name="grading_agent")
|
||||
|
||||
headers = _auth_headers(user)
|
||||
tampered_payload = {
|
||||
"agent_id": agent.id,
|
||||
"stage": "result",
|
||||
"current_question_index": 3,
|
||||
"score": 100,
|
||||
"passed": True,
|
||||
"attempt_count": 1,
|
||||
"join_date": "2026-08-06",
|
||||
"answer_details": [
|
||||
{"question_id": "q1", "selected_option_id": "A", "correct": True},
|
||||
{"question_id": "q2", "selected_option_id": "A", "correct": True},
|
||||
{"question_id": "q3", "selected_option_id": "A", "correct": True},
|
||||
],
|
||||
}
|
||||
|
||||
save_res = client.put("/api/user/training-record/progress", headers=headers, json=tampered_payload)
|
||||
assert save_res.status_code == 200
|
||||
body = save_res.get_json()
|
||||
assert body["score"] == 33
|
||||
assert body["passed"] is False
|
||||
assert body["status"] == "failed"
|
||||
assert body["answer_details"] == [
|
||||
{"question_id": "q1", "selected_option_id": "A", "correct": True},
|
||||
{"question_id": "q2", "selected_option_id": "A", "correct": False},
|
||||
{"question_id": "q3", "selected_option_id": "A", "correct": False},
|
||||
]
|
||||
|
||||
|
||||
def test_training_user_progress_requires_auth_and_valid_payload(client, app):
|
||||
"""培训个人接口必须拒绝未登录请求,并对非法参数返回统一校验错误。"""
|
||||
unauth_res = client.get("/api/user/training-record")
|
||||
|
||||
@@ -138,6 +138,11 @@
|
||||
|
||||
## 3. 范围说明
|
||||
|
||||
### 3.x 员工安全培训资料配置
|
||||
|
||||
- 管理端按公司级、部门级、班组级三级卡片独立增删培训资料,每条资料保存明确的 `training_level`。
|
||||
- 知识库候选仅允许启用的“员工培训”分组中未删除文档的当前版本,员工端按当前 `safetyStage` 动态过滤并展示对应资料。
|
||||
|
||||
### 3.x 文件检核(file_check)补充需求
|
||||
|
||||
- **核心目标**:提供通用文件检核能力(发起检核、查询实时结果、获取报告、可选同步知识库、基于知识库查询历史报告)。对用户统一称为「检核」,不区分排程触发与对话触发等实现方式。
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训配置管理 | 已实现 | `TrainingConfigResource` 增加 `training_level`;管理端按公司级、部门级、班组级卡片独立增删资料;知识库候选仅允许“员工培训”分组内未删除文档的当前版本;员工端按 `safetyStage` 动态展示当前级别资料 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
| 培训业务闭环整改清单 | 已文档化 | 见 [docs/新人入职培训Agent_闭环整改清单.md](新人入职培训Agent_闭环整改清单.md) |
|
||||
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
员工培训增加安全培训功能
|
||||
|
||||
## 安全培训规则与落地方案(已确认)
|
||||
|
||||
> 本节结合现有培训工作区、后端培训记录、知识库、平台应用说明和题库导入能力,统一安全培训业务规则。C-01 至 C-12 已确认,自 2026-08-06 起作为首期需求、技术设计、任务拆分和验收基线。
|
||||
|
||||
### 一、目标与范围
|
||||
|
||||
1. 培训能力采用“培训类型”扩展,首期类型编码固定为 `onboarding`(入职培训)和 `safety`(安全培训)。
|
||||
2. 后续可增加质量培训、合规培训、岗位培训等类型;新增类型必须具备独立规则、资料、题库、版本和培训记录,不得复制安全培训固定逻辑。
|
||||
3. 同一员工可同时参加多种培训,培训记录至少按“员工 + 培训类型 + 培训版本”隔离。
|
||||
4. 安全培训首期包含公司级、部门级、班组级三级教育,以及分级学习、培训总结、可配置考试、补考、完成记录和 HR 统计。
|
||||
5. `TrainingConfigResource.training_level` 固定使用 `company`、`department`、`team`;管理端以三级卡片维护资料,员工端按当前 `safetyStage` 过滤。
|
||||
|
||||
### 二、安全培训三级结构
|
||||
|
||||
| 顺序 | 编码 | 名称 | 内容范围 |
|
||||
| -- | ------------ | ----- | ----------------------------- |
|
||||
| 1 | `company` | 公司级教育 | 政策法规、公司制度、职业卫生、危险因素、应急和事故案例 |
|
||||
| 2 | `department` | 部门级教育 | 部门生产特点、岗位风险、操作规程、设施器材、应急处置和案例 |
|
||||
| 3 | `team` | 班组级教育 | 班组工艺、岗位操作、设备设施、危害防范、报告和现场应急 |
|
||||
|
||||
1. 默认按“公司级 → 部门级 → 班组级”顺序解锁。
|
||||
2. 默认统一考试模式下,上一级学习完成后解锁下一级;三级学习全部完成后进入一次统一考试。
|
||||
3. 配置为独立考试模式时,上一级完成学习且考试通过后才解锁下一级;三级均通过后进入整体完成状态。
|
||||
4. 部门级默认适用于全部门,同时保留按部门配置能力;班组级首期允许不启用班组匹配。启用组织匹配但未找到适用内容时显示“待管理员配置”,不得静默套用其他组织资料。
|
||||
5. 三级结构作为安全培训的可配置阶段实现,不在通用培训页面中硬编码,避免阻碍后续培训类型扩展。
|
||||
|
||||
### 三、学员端流程
|
||||
|
||||
```text
|
||||
进入安全培训
|
||||
→ 读取适用于当前员工的已发布版本
|
||||
→ 展示当前可学习级别
|
||||
→ 查看知识库资料并学习安全培训视频
|
||||
→ 完成学习确认
|
||||
→ 阅读本级培训总结
|
||||
→ 根据考试模式进入统一考试或本级考试
|
||||
→ 服务端判卷并保存考试结果
|
||||
→ 通过:解锁下一级或生成安全培训完成记录
|
||||
→ 未通过:显示结果并按规则补考
|
||||
```
|
||||
|
||||
1. 原“培训须知”统一改为“培训总结”,按公司级、部门级、班组级动态展示对应内容。
|
||||
2. 每一级展示独立资料清单,至少包含资料名称、类型、来源、更新时间、状态和查看操作。
|
||||
3. 视频播放、资料阅读、总结确认和考试均显示明确状态;刷新或重新登录后从服务端恢复级别、阶段和题号。
|
||||
4. 资料未配置、已停用、培训版本失效或接口异常时,阻止进入考试并展示明确原因。
|
||||
5. 学员只能读取本人被分配或规则匹配的培训,不得通过修改培训类型、级别或 URL 获取未授权内容。
|
||||
6. 学习资料首期仅支持在线查看,不展示源文件下载入口。
|
||||
|
||||
### 四、资料来源与绑定规则
|
||||
|
||||
| 资料类型 | 唯一来源 | 现有能力 | 正式绑定要求 |
|
||||
| -------------------- | ------------ | ------------------------------- | -------------------- |
|
||||
| 安全培训视频 | 平台应用说明 | `AgentGuide` / MinIO | 绑定培训类型、级别、版本,支持排序和启停 |
|
||||
| PDF、Word、Excel 等学习资料 | 员工培训知识库 | `KbGroup` / `KbDocument` / 文档版本 | 绑定培训类型、级别、适用部门或岗位 |
|
||||
| 试题原文件 | 培训管理引用的知识库文件 | 复用 PDF 文本解析和 OCR 回退 | 绑定级别,解析后必须人工复核 |
|
||||
| 正式题库 | 培训管理发布结果 | 复用现有结构化题库 | 具备题库版本、状态、题量、及格线和发布人 |
|
||||
|
||||
1. `training_safety_video`、`training_safety_pdf` 作为现有数据兼容标识,不能替代“培训类型 + 级别 + 版本”绑定。
|
||||
2. 文件资料只能来自指定“员工培训知识库”或明确授权的子分组,普通知识库资料不得自动混入安全培训。
|
||||
3. 管理端候选文档必须属于启用的“员工培训” `KbGroup`、逻辑文档未删除且为当前版本;后端保存时再次校验该约束。
|
||||
4. 知识库文件更新后,已发布培训继续使用原版本快照;新版本发布后,新参训员工使用新版本,历史记录保留旧版本。
|
||||
5. OCR 低置信度、解析失败或无法确认答案的题目进入待复核,不得直接进入正式考试。
|
||||
6. Dify 负责培训资料问答、知识解释和 HR 自然语言查询;阶段推进、抽题、判卷、成绩、权限和事实落库由 HXOPS 控制。
|
||||
|
||||
### 五、培训管理页面
|
||||
|
||||
新增独立“培训管理”页面,作为培训业务统一配置入口。Agent 管理仅保留培训能力开关和配置关联;平台应用说明继续负责视频上传,通过培训管理完成业务绑定。
|
||||
|
||||
培训管理至少包含:
|
||||
|
||||
1. 培训类型:名称、编码、说明、启用状态。
|
||||
2. 培训级别:顺序、名称、适用范围和前置级别。
|
||||
3. 培训资料:知识库资料引用、平台视频引用、排序、适用组织、启用状态和版本。
|
||||
4. 题库管理:导入、解析、生成、人工新增、编辑、删除、校验、启用和停用。
|
||||
5. 培训规则:考试模式、及格线、题量、抽题方式、考试次数、补考间隔和完成条件;默认采用“三级学习完成后统一考试”。
|
||||
6. 发布管理:草稿、待复核、已发布、已停用;已发布版本不可直接覆盖。
|
||||
7. 培训记录:按培训类型、级别、部门、员工、状态和时间查询、统计和导出。
|
||||
|
||||
现有 `Agent.extra_config.training_config` 迁移采用“数据盘点 → 映射预览 → 管理员确认 → 写入新配置 → 校验”的流程。无法自动判断级别或归属的数据进入“待分类”,禁止静默归入公司级。
|
||||
|
||||
### 六、考试与成绩规则
|
||||
|
||||
1. 默认采用一套统一题库,三级学习全部完成后统一考试;管理员可切换为每级独立考试,并分别配置各级题库和题量。首期支持单选题和判断题。
|
||||
2. 前端只展示题目并提交答案,服务端根据已发布题库版本重新判卷、计算分数和判定是否通过。
|
||||
3. 服务端不得以客户端提交的 `score`、`passed` 或 `correct` 作为唯一事实来源。
|
||||
4. 每次考试保存培训类型、考试模式、级别(统一考试时为空)、培训版本、题库版本、开始时间、交卷时间、得分、通过结果和逐题答案。
|
||||
5. 默认及格线为 90 分,题量读取当前考试配置。未通过可按配置补考;独立考试模式下未通过不得解锁下一级,补考不能重置已通过级别。
|
||||
6. 通过后重复进入页面不得重置成绩;发布新版本后是否要求重训由版本规则决定。
|
||||
7. 统一考试模式展示一项整体成绩;独立考试模式分别展示三级成绩,整体通过条件为三级均通过。
|
||||
|
||||
### 七、权限与审计
|
||||
|
||||
| 角色 | 学习本人培训 | 查看本人记录 | 配置培训/题库 | 查看全员统计与导出 |
|
||||
| -------- | ------ | ------ | ------- | --------- |
|
||||
| 员工 | 是 | 是 | 否 | 否 |
|
||||
| HR/培训管理员 | 是 | 是 | 是 | 是 |
|
||||
| 系统管理员 | 是 | 是 | 是 | 是 |
|
||||
|
||||
1. 后端统一使用 `training_hr_manage` 校验培训管理、统计和导出权限,不以页面是否隐藏作为安全措施。
|
||||
2. 培训管理员只管理授权培训类型或组织范围;首期若不支持细粒度范围,应明确其拥有全局管理权限。
|
||||
3. 资料、题库、规则、发布和迁移操作记录操作人、时间、变更前后内容和结果。
|
||||
|
||||
### 八、状态与版本
|
||||
|
||||
```text
|
||||
草稿 → 待复核 → 已发布 → 已停用
|
||||
```
|
||||
|
||||
1. 草稿可编辑;进入待复核前必须完成资料完整性和题库校验。
|
||||
2. 已发布版本不可直接修改;修改资料、题库或规则时生成新版本。
|
||||
3. 已停用版本不再分配给新员工,但历史培训记录仍可查询。
|
||||
4. 员工首次开始培训时记录培训版本和题库版本,保证历史成绩可审计。
|
||||
5. 首期预留复训和有效期字段但不启用,不因时间经过自动使已完成记录失效。
|
||||
|
||||
### 九、与现有项目的实施边界
|
||||
|
||||
可直接复用的现有能力:培训工作区、`TrainingRecord` 培训类型隔离、HR 统计导出、`AgentGuide`/MinIO、PDF 文本解析和 OCR 回退。
|
||||
|
||||
以下属于本需求后续建设,当前前端原型不代表已经完成:
|
||||
|
||||
1. 三级级别与阶段进度的服务端持久化。
|
||||
2. 安全培训资料、视频与级别的动态绑定。
|
||||
3. 员工培训知识库与安全培训工作区的正式映射。
|
||||
4. 独立培训管理页面及旧配置迁移。
|
||||
5. 题库、资料和培训规则版本化。
|
||||
6. 服务端判卷、防篡改和每次考试历史。
|
||||
|
||||
### 十、确认结论
|
||||
|
||||
| 编号 | 确认事项 | 建议默认值 | 确认结果 |
|
||||
| ---- | ------------------- | ------------ | ------------------------ |
|
||||
| C-01 | 三级是否固定为公司级、部门级、班组级 | 是 | 是 |
|
||||
| C-02 | 三级是否必须按顺序完成 | 是 | 是 |
|
||||
| C-03 | 部门级/班组级如何匹配员工 | 部门必配,班组首期可选 | 默认配置全部门 |
|
||||
| C-04 | 每级是否独立考试、独立成绩和补考 | 是 | 是(可配置是否独立考试,默认统一完成后一次考试) |
|
||||
| C-05 | 默认及格线和每级题量 | 90 分;题量按级别配置 | 是(默认统一一套题库) |
|
||||
| C-06 | 未通过是否允许进入下一级 | 否 | 否 |
|
||||
| C-07 | 是否需要年度复训和有效期 | 首期不启用,预留字段 | 首期不启用,预留字段 |
|
||||
| C-08 | 试题原文件是否统一从员工培训知识库引用 | 是 | 是 |
|
||||
| C-09 | 学习资料是否允许下载 | 默认仅在线查看 | 默认仅在线查看 |
|
||||
| C-10 | 旧员工培训配置迁移后的归属 | 先预览再确认 | 先预览再确认 |
|
||||
| C-11 | 是否需要截止日期、逾期和企业微信提醒 | 首期不纳入 | 首期不纳入 |
|
||||
| C-12 | 是否需要证书或完成凭证 | 首期仅生成完成记录 | 首期仅生成完成记录 |
|
||||
|
||||
### 十一、验收标准
|
||||
|
||||
1. 员工只能看到已发布且适用于本人的安全培训版本。
|
||||
2. 公司级、部门级、班组级资料和总结相互独立并按顺序解锁;默认三级学习完成后统一考试,切换独立考试模式后按级考试。
|
||||
3. 刷新、重新登录或接口重试后,培训版本、考试模式、级别、阶段、题号和答题记录不丢失。
|
||||
4. 统一考试达到配置及格线后生成完成记录;独立考试模式下未通过本级考试不能进入下一级。
|
||||
5. HR 可按培训类型、级别、部门、员工、状态和时间查询并导出记录。
|
||||
6. 管理员可在培训管理页面完成资料绑定、题库复核、规则设置和版本发布停用。
|
||||
7. 视频只能来自平台应用说明,文件资料只能来自指定员工培训知识库,来源不符合规则时不可发布。
|
||||
8. 历史记录显示当时的培训版本、题库版本、考试模式、考试次数和成绩,不因后续题库修改而变化。
|
||||
9. 普通员工无法访问培训管理、全员统计和导出接口。
|
||||
10. 学习资料仅提供在线查看,不提供源文件下载;旧配置必须预览确认后迁移。
|
||||
11. 首期不提供截止日期、逾期状态、企业微信提醒、年度复训和证书,仅生成可审计的培训完成记录。
|
||||
|
||||
### 十二、实施任务与验收矩阵
|
||||
|
||||
| 阶段 | 任务 | 主要交付物 | 验收重点 |
|
||||
| --- | --- | --- | --- |
|
||||
| P0-数据基线 | 建立培训定义、版本、级别、资料引用、题库和考试历史模型 | Alembic 迁移、模型测试、初始化安全培训配置 | 三级编码固定;版本可发布/停用;历史记录不被新版本覆盖 |
|
||||
| P0-考试安全 | 将前端快照保存改为服务端受控动作和服务端判卷 | 目录、学习完成、考试、交卷、补考接口 | 客户端篡改 `score/passed/correct` 不影响服务端结果;统一考试默认 90 分 |
|
||||
| P0-学员流程 | 接入三级状态、统一考试默认模式和独立考试可配置模式 | 前端 composable、API 类型和页面状态 | 顺序解锁;刷新恢复版本、级别、阶段和题号;未通过独立考试不得推进 |
|
||||
| P1-资料绑定 | 接入员工培训知识库资料和平台应用说明视频 | 资料绑定接口、在线查看接口、来源校验 | 普通知识库资料不可混入;不提供下载;停用资料不可进入考试 |
|
||||
| P1-培训管理 | 新增独立培训管理页面,迁移 Agent 管理中的正式配置入口 | 管理路由、类型/级别/资料/题库/规则/版本页面 | 可完成草稿、待复核、发布、停用;已发布版本不可覆盖 |
|
||||
| P1-旧配置迁移 | 对 `extra_config.training_config` 进行盘点和确认迁移 | 迁移预览、待分类清单、执行结果和审计 | 未确认不得写入;无法归属数据不静默归类;迁移结果可复核 |
|
||||
| P1-管理统计 | 扩展 HR 查询、统计和导出 | 类型、版本、级别、部门、状态、时间筛选 | 统一考试展示整体成绩;独立考试展示级别成绩;权限统一校验 |
|
||||
| P2-回归验收 | 完成前后端自动化测试和关键页面回归 | API 测试、服务测试、前端组件/流程测试 | 正常、补考、刷新恢复、越权、版本切换、资料来源和迁移场景全部通过 |
|
||||
|
||||
#### P0 接口验收矩阵
|
||||
|
||||
| 场景 | 请求结果 | 必须满足 |
|
||||
| --- | --- | --- |
|
||||
| 未登录读取安全培训 | 401 | 不返回培训版本、资料或题库 |
|
||||
| 普通员工读取本人适用培训 | 200 | 仅返回已发布且匹配全部门规则的内容 |
|
||||
| 伪造培训类型或版本 | 403/404 | 不得读取未授权培训 |
|
||||
| 完成公司级学习 | 200 | 统一考试模式解锁部门级;独立考试模式进入公司级考试 |
|
||||
| 未完成前置级别读取下一级 | 409 | 返回前置条件,不返回可考试题目 |
|
||||
| 统一考试交卷 | 200 | 服务端按统一题库判卷,达到 90 分才生成完成记录 |
|
||||
| 独立考试未通过 | 200 | 保留本级进度,禁止解锁下一等级,允许按配置补考 |
|
||||
| 客户端提交虚假分数 | 200/422 | 服务端重新计算,客户端分数不作为结果依据 |
|
||||
| 员工访问管理接口 | 403 | 培训管理、全员统计和导出均被拒绝 |
|
||||
| 旧配置迁移执行前 | 409 | 未完成管理员确认时不得写入正式培训配置 |
|
||||
|
||||
#### 首期明确不开发
|
||||
|
||||
以下内容不进入本阶段开发任务和验收范围:年度复训触发、有效期自动失效、截止日期、逾期状态、企业微信提醒、证书生成、证书下载和学习资料源文件下载。
|
||||
10. 本节确认结论已作为首期需求基线,并据此拆分开发任务和测试用例。
|
||||
|
||||
<br />
|
||||
|
||||
前端页面如图一所示
|
||||
|
||||
一、功能点说明
|
||||
|
||||
1.分为三级安全培训
|
||||
|
||||
2.每一级安全培训都有独立的学习资料
|
||||
|
||||
3.学习资料文件全部来源于员工培训知识库
|
||||
|
||||
4.所有视频资料来源于“平台应用说明”
|
||||
|
||||
<br />
|
||||
|
||||
二、前端页面说明
|
||||
|
||||
 =>
|
||||
|
||||
const ProcurementContractPage = () =>
|
||||
import("@/features/admin/modules/procurement-contract/ProcurementContractPage.vue");
|
||||
const TrainingConfigPage = () =>
|
||||
import("@/features/admin/modules/training-config/TrainingConfigPage.vue");
|
||||
|
||||
export const adminRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
@@ -351,6 +353,16 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
title: "admin.nav.procurementContract",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "training-config",
|
||||
name: "AdminTrainingConfig",
|
||||
component: TrainingConfigPage,
|
||||
meta: {
|
||||
requiresAdmin: true,
|
||||
adminModule: "training_config",
|
||||
title: "admin.nav.trainingConfig",
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "reports/:table?",
|
||||
name: "AdminReports",
|
||||
|
||||
@@ -73,6 +73,7 @@ export const config = {
|
||||
schedules: true, // 定时任务
|
||||
shipping_inventory: true, // 货代配置
|
||||
procurement_contract: true, // 采购合同审查(模板库 + 历史)
|
||||
training_config: true,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -18,10 +18,14 @@ import type {
|
||||
UsageReport,
|
||||
UsageRangeKey,
|
||||
} from '../types/report.types';
|
||||
import type { TrainingConfig, TrainingConfigPayload, TrainingResourceCandidates } from '../types/training-config.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
|
||||
|
||||
|
||||
export type ShippingInventoryReadinessCheck = {
|
||||
code: string;
|
||||
status: 'passed' | 'pending' | 'failed' | 'stale' | 'empty';
|
||||
@@ -398,6 +402,49 @@ export const saveShippingInventoryExternalMapping = (payload: Record<string, unk
|
||||
export const deleteShippingInventoryExternalMapping = (id: number) => requestJson<void>(
|
||||
`/api/admin/shipping-notice/external-mappings/${id}`, { method: 'DELETE', ...auth() },
|
||||
);
|
||||
export const listAdminTrainingConfigs = () =>
|
||||
requestJson<TrainingConfig[]>('/api/admin/training-configs', auth());
|
||||
|
||||
export const listAdminTrainingResourceCandidates = () =>
|
||||
requestJson<TrainingResourceCandidates>('/api/admin/training-configs/resource-candidates', auth());
|
||||
|
||||
export interface TrainingQuestionBankParseResult {
|
||||
question_bank: unknown[];
|
||||
parsed_count: number;
|
||||
skipped_question_numbers: number[];
|
||||
kb_document_version_id: number;
|
||||
source_file_name: string;
|
||||
version_no: number;
|
||||
extraction_mode: 'pdf_text' | 'ocr' | 'ocr_fallback';
|
||||
extraction_warnings: string[];
|
||||
}
|
||||
|
||||
export const parseAdminTrainingQuestionBank = (kbDocumentVersionId: number) =>
|
||||
requestJson<TrainingQuestionBankParseResult>('/api/admin/training-configs/question-bank/parse', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify({ kb_document_version_id: kbDocumentVersionId }),
|
||||
});
|
||||
|
||||
export const createAdminTrainingConfig = (payload: TrainingConfigPayload) =>
|
||||
requestJson<TrainingConfig>('/api/admin/training-configs', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateAdminTrainingConfig = (id: number, payload: TrainingConfigPayload) =>
|
||||
requestJson<TrainingConfig>(`/api/admin/training-configs/${id}`, {
|
||||
method: 'PUT',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const deleteAdminTrainingConfig = (id: number) =>
|
||||
requestJson<{ success: boolean }>(`/api/admin/training-configs/${id}`, {
|
||||
method: 'DELETE',
|
||||
...auth(),
|
||||
});
|
||||
|
||||
// Users
|
||||
export const listAdminUsers = () => requestJson<AdminUserRow[]>('/api/admin/users', auth());
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
LayoutDashboard, UserPlus, UserCog, Building, Bot, FileText,
|
||||
Settings2, Megaphone, MessageCircleQuestion, Link2, Users, ShieldCheck, BarChart2, AppWindow,
|
||||
ScrollText, ExternalLink, PackageSearch,
|
||||
ScrollText, ExternalLink, PackageSearch, GraduationCap,
|
||||
} from 'lucide-vue-next';
|
||||
import type { Component } from 'vue';
|
||||
import { config } from '@/config';
|
||||
@@ -43,6 +43,7 @@ const iconMap: Record<AdminModuleId, Component> = {
|
||||
permissions: Users,
|
||||
platform_apps: AppWindow,
|
||||
procurement_contract: ScrollText,
|
||||
training_config: GraduationCap,
|
||||
requests: ShieldCheck,
|
||||
reports: BarChart2,
|
||||
shipping_inventory: PackageSearch,
|
||||
|
||||
@@ -42,7 +42,7 @@ export interface ShippingConfigSubModuleMeta {
|
||||
|
||||
/** 已独立拆分的模块(全部 admin 模块均已拆分) */
|
||||
export const STANDALONE_ADMIN_MODULES = new Set<AdminModuleId>([
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports',
|
||||
'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'linked_services', 'platform_apps', 'shipping_inventory', 'procurement_contract', 'reports','training_config'
|
||||
]);
|
||||
|
||||
export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
@@ -61,6 +61,7 @@ export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [
|
||||
{ id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' },
|
||||
{ id: 'platform_apps', routeName: 'AdminPlatformApps', path: 'platform-apps', labelKey: 'admin.nav.platformApps', configKey: 'platform_apps' },
|
||||
{ id: 'procurement_contract', routeName: 'AdminProcurementContract', path: 'procurement-contract', labelKey: 'admin.nav.procurementContract', configKey: 'procurement_contract' },
|
||||
{ id: 'training_config', routeName: 'AdminTrainingConfig', path: 'training-config', labelKey: 'admin.nav.trainingConfig', configKey: 'training_config' },
|
||||
{ id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' },
|
||||
];
|
||||
|
||||
|
||||
@@ -38,6 +38,31 @@ const uploadError = ref('');
|
||||
const deleteDialogOpen = ref(false);
|
||||
const pendingDeleteGuideId = ref<number | null>(null);
|
||||
|
||||
const safetyVideoUsages = new Set([
|
||||
'training_safety_video',
|
||||
'training_safety_company_video',
|
||||
'training_safety_department_video',
|
||||
'training_safety_team_video',
|
||||
]);
|
||||
|
||||
const isVideoUsage = (usage: string) => usage === 'training_video' || safetyVideoUsages.has(usage);
|
||||
const isPdfUsage = (usage: string) => usage === 'training_exam_pdf' || usage === 'training_safety_pdf';
|
||||
|
||||
/**
|
||||
* 把指南用途编码翻译成管理端可读名称。
|
||||
* AI 触发时机:平台应用说明列表与弹窗下拉都依赖这层映射,新增资料用途时必须统一从这里出文案,避免表格和表单各自写死分叉。
|
||||
*/
|
||||
const getGuideUsageLabel = (usage: string) => {
|
||||
if (usage === 'training_video') return t('admin.platformApps.trainingVideo');
|
||||
if (usage === 'training_exam_pdf') return t('admin.platformApps.trainingExamPdf');
|
||||
if (usage === 'training_safety_company_video') return t('admin.platformApps.trainingSafetyCompanyVideo');
|
||||
if (usage === 'training_safety_department_video') return t('admin.platformApps.trainingSafetyDepartmentVideo');
|
||||
if (usage === 'training_safety_team_video') return t('admin.platformApps.trainingSafetyTeamVideo');
|
||||
if (usage === 'training_safety_video') return t('admin.platformApps.trainingSafetyVideo');
|
||||
if (usage === 'training_safety_pdf') return t('admin.platformApps.trainingSafetyPdf');
|
||||
return t('admin.platformApps.generalGuide');
|
||||
};
|
||||
|
||||
/**
|
||||
* 拉取 Agent 列表并默认选中第一项,再加载其指南。
|
||||
*/
|
||||
@@ -134,10 +159,10 @@ const handleFileUpload = async (event: Event) => {
|
||||
form.value.file_path = res.file_path;
|
||||
form.value.file_type = res.file_type;
|
||||
form.value.file_size = res.file_size;
|
||||
if (form.value.guide_usage === 'training_video' && res.file_type !== 'video') {
|
||||
if (isVideoUsage(form.value.guide_usage) && res.file_type !== 'video') {
|
||||
form.value.guide_usage = 'general';
|
||||
}
|
||||
if (form.value.guide_usage === 'training_exam_pdf' && res.file_type !== 'pdf') {
|
||||
if (isPdfUsage(form.value.guide_usage) && res.file_type !== 'pdf') {
|
||||
form.value.guide_usage = 'general';
|
||||
}
|
||||
if (!form.value.file_name) {
|
||||
@@ -297,9 +322,7 @@ const getIcon = (type: string) => {
|
||||
<div class="text-xs text-muted mt-1 truncate max-w-[200px]">{{ guide.remark }}</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-muted">
|
||||
<span v-if="guide.guide_usage === 'training_video'">{{ t('admin.platformApps.trainingVideo') }}</span>
|
||||
<span v-else-if="guide.guide_usage === 'training_exam_pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</span>
|
||||
<span v-else>{{ t('admin.platformApps.generalGuide') }}</span>
|
||||
<span>{{ getGuideUsageLabel(guide.guide_usage || 'general') }}</span>
|
||||
</td>
|
||||
<td class="px-6 py-4">
|
||||
<span class="inline-flex items-center px-2 py-1 rounded-md text-xs font-medium bg-brand-50 text-brand-700 border border-brand-100">
|
||||
@@ -372,6 +395,11 @@ const getIcon = (type: string) => {
|
||||
<option value="general">{{ t('admin.platformApps.generalGuide') }}</option>
|
||||
<option value="training_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingVideo') }}</option>
|
||||
<option value="training_exam_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingExamPdf') }}</option>
|
||||
<option value="training_safety_company_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyCompanyVideo') }}</option>
|
||||
<option value="training_safety_department_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyDepartmentVideo') }}</option>
|
||||
<option value="training_safety_team_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyTeamVideo') }}</option>
|
||||
<option value="training_safety_video" :disabled="form.file_type !== 'video'">{{ t('admin.platformApps.trainingSafetyVideo') }}</option>
|
||||
<option value="training_safety_pdf" :disabled="form.file_type !== 'pdf'">{{ t('admin.platformApps.trainingSafetyPdf') }}</option>
|
||||
</select>
|
||||
<p class="text-xs text-muted">{{ t('admin.platformApps.guideUsageHint') }}</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/admin/modules/training-config/TrainingConfigPage.vue
|
||||
* 用途:提供培训类型、基础规则、三级学习资料、考试题库与复盘内容的一体化后台配置界面。
|
||||
* 依赖:admin.api 培训配置接口、training-config.types、TrainingTypeFormModal 与通用消息/删除确认组件。
|
||||
* 逻辑:左侧切换培训类型,右侧编辑完整配置;保存时将题目同步到 settings 与内嵌题目资源后提交既有 API。
|
||||
*/
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import {
|
||||
BookOpen,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
ClipboardCheck,
|
||||
Edit,
|
||||
FileQuestion,
|
||||
FileText,
|
||||
Layers3,
|
||||
Library,
|
||||
ListChecks,
|
||||
Plus,
|
||||
Save,
|
||||
Settings2,
|
||||
ShieldCheck,
|
||||
Trash2,
|
||||
Video,
|
||||
} from 'lucide-vue-next';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import {
|
||||
createAdminTrainingConfig,
|
||||
deleteAdminTrainingConfig,
|
||||
listAdminTrainingConfigs,
|
||||
listAdminTrainingResourceCandidates,
|
||||
parseAdminTrainingQuestionBank,
|
||||
updateAdminTrainingConfig,
|
||||
} from '../../api/admin.api';
|
||||
import type { TrainingConfig, TrainingConfigPayload, TrainingLevel } from '../../types/training-config.types';
|
||||
import TrainingTypeFormModal from './components/TrainingTypeFormModal.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
const configs = ref<TrainingConfig[]>([]);
|
||||
const selectedId = ref<number | null>(null);
|
||||
const isLoading = ref(true);
|
||||
const isSaving = ref(false);
|
||||
const showTypeEditor = ref(false);
|
||||
const editingType = ref(false);
|
||||
const deleteTarget = ref<TrainingConfig | null>(null);
|
||||
const typeForm = ref({ training_type: '', name: '' });
|
||||
const questionJsonText = ref('[]');
|
||||
const questionSourceVersionId = ref<number | null>(null);
|
||||
const isParsingQuestions = ref(false);
|
||||
const questionParseMeta = ref<{ mode: string; fileName: string; skipped: number[] } | null>(null);
|
||||
const candidates = ref({ guides: [], documents: [], training_exam_documents: [] } as Awaited<ReturnType<typeof listAdminTrainingResourceCandidates>>);
|
||||
|
||||
const selected = computed(() => configs.value.find((item) => item.id === selectedId.value) || null);
|
||||
const form = ref<TrainingConfigPayload>(emptyForm());
|
||||
const contentResources = computed(() => form.value.resources.filter((resource) => resource.resource_type !== 'inline_questions'));
|
||||
const trainingLevels: TrainingLevel[] = ['company', 'department', 'team'];
|
||||
const guideGroups = computed(() => {
|
||||
const groupUsages = [
|
||||
{ key: 'company', usage: 'training_safety_company_video' },
|
||||
{ key: 'department', usage: 'training_safety_department_video' },
|
||||
{ key: 'team', usage: 'training_safety_team_video' },
|
||||
];
|
||||
const grouped = groupUsages.map((group) => ({
|
||||
key: group.key,
|
||||
items: candidates.value.guides.filter((guide) => guide.guide_usage === group.usage),
|
||||
}));
|
||||
const groupedUsages = new Set(groupUsages.map((group) => group.usage));
|
||||
grouped.push({
|
||||
key: 'other',
|
||||
items: candidates.value.guides.filter((guide) => !groupedUsages.has(guide.guide_usage)),
|
||||
});
|
||||
return grouped.filter((group) => group.items.length > 0);
|
||||
});
|
||||
const questionCount = computed(() => {
|
||||
try {
|
||||
const questions = JSON.parse(questionJsonText.value);
|
||||
return Array.isArray(questions) ? questions.length : 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
const activeSection = ref('basic');
|
||||
const sectionItems = computed(() => [
|
||||
{ id: 'basic', label: t('admin.trainingConfig.sections.basicTitle'), icon: Layers3 },
|
||||
{ id: 'resources', label: t('admin.trainingConfig.sections.resourcesTitle'), icon: Library },
|
||||
{ id: 'exam', label: t('admin.trainingConfig.sections.examTitle'), icon: FileQuestion },
|
||||
{ id: 'review', label: t('admin.trainingConfig.sections.reviewTitle'), icon: ClipboardCheck },
|
||||
]);
|
||||
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);
|
||||
|
||||
/** 创建新增培训类型所需的完整默认配置,确保沿用后端既有字段契约。 */
|
||||
function emptyForm(): TrainingConfigPayload {
|
||||
return {
|
||||
training_type: '',
|
||||
name: '',
|
||||
version: 'v1.0',
|
||||
status: 'draft',
|
||||
pass_score: 90,
|
||||
settings: { exam_mode: 'unified', questions: [] },
|
||||
resources: [],
|
||||
};
|
||||
}
|
||||
|
||||
const showDeleteConfirm = computed({
|
||||
get: () => deleteTarget.value !== null,
|
||||
set: (visible: boolean) => {
|
||||
if (!visible) deleteTarget.value = null;
|
||||
},
|
||||
});
|
||||
|
||||
/** 将选中的服务端配置复制到编辑表单,并兼容 settings 与内嵌资源中的历史题库数据。 */
|
||||
const selectConfig = (config: TrainingConfig) => {
|
||||
const inlineQuestions = config.resources.find((resource) => resource.resource_type === 'inline_questions')?.inline_questions;
|
||||
const questions = Array.isArray(inlineQuestions) ? inlineQuestions : Array.isArray(config.settings.questions) ? config.settings.questions : [];
|
||||
selectedId.value = config.id;
|
||||
form.value = {
|
||||
training_type: config.training_type,
|
||||
name: config.name,
|
||||
version: config.version,
|
||||
status: config.status,
|
||||
pass_score: config.pass_score,
|
||||
settings: { ...config.settings, questions },
|
||||
resources: config.resources.map((resource) => ({ ...resource })),
|
||||
};
|
||||
questionJsonText.value = JSON.stringify(questions, null, 2);
|
||||
questionSourceVersionId.value = null;
|
||||
questionParseMeta.value = null;
|
||||
};
|
||||
|
||||
/** 从已选择的员工培训知识库当前 PDF 解析题库,并将结果回填到可继续手工编辑的 JSON。 */
|
||||
const parseQuestionBank = async () => {
|
||||
if (!questionSourceVersionId.value) {
|
||||
msg.warning(t('admin.trainingConfig.messages.questionSourceRequired'));
|
||||
return;
|
||||
}
|
||||
isParsingQuestions.value = true;
|
||||
try {
|
||||
const result = await parseAdminTrainingQuestionBank(questionSourceVersionId.value);
|
||||
questionJsonText.value = JSON.stringify(result.question_bank, null, 2);
|
||||
questionParseMeta.value = { mode: result.extraction_mode, fileName: result.source_file_name, skipped: result.skipped_question_numbers };
|
||||
msg.success(t('admin.trainingConfig.messages.parseSuccess', { count: result.parsed_count }));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.parseFailed'));
|
||||
} finally {
|
||||
isParsingQuestions.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 将 settings 中的数组字段转换为多行文本供复盘表单编辑。 */
|
||||
const settingText = (key: string) => {
|
||||
const value = form.value.settings[key];
|
||||
return Array.isArray(value) ? value.join('\n') : String(value || '');
|
||||
};
|
||||
|
||||
/** 将复盘区域的多行文本清洗为非空数组并写回 settings。 */
|
||||
const updateSettingText = (key: string, value: string) => {
|
||||
form.value.settings[key] = value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
|
||||
};
|
||||
|
||||
const settingSummaryByStageText = (level: string) => {
|
||||
const summaries = (form.value.settings.summaryByStage as Record<string, string[]>) || {};
|
||||
const value = summaries[level];
|
||||
return Array.isArray(value) ? value.join('\n') : String(value || '');
|
||||
};
|
||||
|
||||
const updateSettingSummaryByStageText = (level: string, value: string) => {
|
||||
if (!form.value.settings.summaryByStage) {
|
||||
form.value.settings.summaryByStage = {};
|
||||
}
|
||||
const summaries = form.value.settings.summaryByStage as Record<string, string[]>;
|
||||
summaries[level] = value.split(/\r?\n/).map((item) => item.trim()).filter(Boolean);
|
||||
};
|
||||
|
||||
/** 并行加载培训配置与可选资料,并默认打开首个培训类型。 */
|
||||
const load = async () => {
|
||||
isLoading.value = true;
|
||||
try {
|
||||
const [loadedConfigs, loadedCandidates] = await Promise.all([
|
||||
listAdminTrainingConfigs(),
|
||||
listAdminTrainingResourceCandidates(),
|
||||
]);
|
||||
configs.value = loadedConfigs;
|
||||
candidates.value = loadedCandidates;
|
||||
const firstConfig = configs.value[0];
|
||||
if (firstConfig) selectConfig(firstConfig);
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.loadFailed'));
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 打开新增培训类型弹窗并重置类型表单。 */
|
||||
const openCreate = () => {
|
||||
editingType.value = false;
|
||||
typeForm.value = { training_type: '', name: '' };
|
||||
showTypeEditor.value = true;
|
||||
};
|
||||
|
||||
/** 使用当前培训类型信息打开编辑弹窗。 */
|
||||
const editType = () => {
|
||||
if (selected.value) {
|
||||
editingType.value = true;
|
||||
typeForm.value = { training_type: selected.value.training_type, name: selected.value.name };
|
||||
showTypeEditor.value = true;
|
||||
}
|
||||
};
|
||||
|
||||
/** 校验并新增或更新培训类型,成功后刷新列表并保持当前选中项。 */
|
||||
const saveType = async () => {
|
||||
const rawType = typeForm.value.training_type.trim();
|
||||
typeForm.value.training_type = ({
|
||||
'入职培训': 'onboarding',
|
||||
'新人培训': 'onboarding',
|
||||
'安全培训': 'safety',
|
||||
} as Record<string, string>)[rawType] || rawType.toLowerCase();
|
||||
if (!['onboarding', 'safety'].includes(typeForm.value.training_type) || !typeForm.value.name.trim()) {
|
||||
msg.warning(t('admin.trainingConfig.messages.typeRequired'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const existing = editingType.value ? selected.value : null;
|
||||
const payload = existing ? { ...form.value, training_type: typeForm.value.training_type, name: typeForm.value.name } : {
|
||||
...emptyForm(), training_type: typeForm.value.training_type, name: typeForm.value.name,
|
||||
};
|
||||
const saved = existing ? await updateAdminTrainingConfig(existing.id, payload) : await createAdminTrainingConfig(payload);
|
||||
await load();
|
||||
selectConfig(saved);
|
||||
showTypeEditor.value = false;
|
||||
msg.success(t('admin.trainingConfig.messages.saved'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 校验题目 JSON,将题库双写至兼容字段后通过既有更新接口保存完整配置。 */
|
||||
const saveConfig = async () => {
|
||||
if (!selected.value) return;
|
||||
try {
|
||||
const questions = JSON.parse(questionJsonText.value);
|
||||
if (!Array.isArray(questions)) throw new Error();
|
||||
form.value.settings.questions = questions;
|
||||
const inlineResource = form.value.resources.find((resource) => resource.resource_type === 'inline_questions');
|
||||
if (questions.length) {
|
||||
if (inlineResource) inlineResource.inline_questions = questions;
|
||||
else form.value.resources.push({ resource_type: 'inline_questions', title: t('admin.trainingConfig.questionBankTitle'), sort_order: 1000, inline_questions: questions });
|
||||
} else if (inlineResource) {
|
||||
form.value.resources = form.value.resources.filter((resource) => resource !== inlineResource);
|
||||
}
|
||||
} catch {
|
||||
msg.warning(t('admin.trainingConfig.messages.invalidQuestions'));
|
||||
return;
|
||||
}
|
||||
isSaving.value = true;
|
||||
try {
|
||||
const saved = await updateAdminTrainingConfig(selected.value.id, form.value);
|
||||
await load();
|
||||
selectConfig(saved);
|
||||
msg.success(t('admin.trainingConfig.messages.saved'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
|
||||
} finally {
|
||||
isSaving.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 向指定培训级别新增一条资料绑定。
|
||||
* AI 触发时机:管理员点击三级卡片内的“添加资料”时调用,新增项必须携带对应 training_level,避免员工端跨级展示。
|
||||
*/
|
||||
const addResource = (trainingLevel: TrainingLevel) => {
|
||||
form.value.resources.push({ resource_type: 'agent_guide', training_level: trainingLevel, title: '', required_duration: 0, sort_order: form.value.resources.length });
|
||||
};
|
||||
|
||||
/** 返回指定级别的资料,供三级卡片独立渲染与增删。 */
|
||||
const resourcesByLevel = (trainingLevel: TrainingLevel) => contentResources.value.filter((resource) => resource.training_level === trainingLevel);
|
||||
|
||||
/** 从当前编辑表单中移除指定资料绑定。 */
|
||||
const removeResource = (resource: TrainingConfigPayload['resources'][number]) => {
|
||||
form.value.resources = form.value.resources.filter((item) => item !== resource);
|
||||
};
|
||||
|
||||
/** 切换资料类型时清空旧关联主键,避免提交互斥资源字段。 */
|
||||
const updateResourceType = (resource: TrainingConfigPayload['resources'][number]) => {
|
||||
resource.agent_guide_id = undefined;
|
||||
resource.kb_document_version_id = undefined;
|
||||
};
|
||||
|
||||
const scrollToSection = (sectionId: string) => {
|
||||
activeSection.value = sectionId;
|
||||
document.getElementById(`training-section-${sectionId}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
};
|
||||
|
||||
/** 按发布状态返回统一的后台状态标签颜色。 */
|
||||
const statusClass = (status: TrainingConfig['status']) => {
|
||||
if (status === 'published') return 'alert-success';
|
||||
if (status === 'archived') return 'bg-surface-strong text-muted ring-1 ring-inset ring-default';
|
||||
return 'alert-warning';
|
||||
};
|
||||
|
||||
/** 删除确认后的当前培训配置,并刷新左侧类型列表。 */
|
||||
const deleteType = async () => {
|
||||
if (!deleteTarget.value) return;
|
||||
try {
|
||||
await deleteAdminTrainingConfig(deleteTarget.value.id);
|
||||
deleteTarget.value = null;
|
||||
await load();
|
||||
msg.success(t('admin.trainingConfig.messages.deleted'));
|
||||
} catch (error) {
|
||||
msg.error(error instanceof Error ? error.message : t('admin.trainingConfig.messages.saveFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => void load());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="page-shell min-h-full px-1 py-1 animate-fade-in-up">
|
||||
<div class="mb-6 flex flex-col gap-1 px-1 sm:px-2">
|
||||
<p class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">{{ t('admin.trainingConfig.eyebrow') }}</p>
|
||||
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div>
|
||||
<h1 class="page-title">{{ t('admin.trainingConfig.title') }}</h1>
|
||||
<p class="section-desc mt-2 max-w-2xl leading-6">{{ t('admin.trainingConfig.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="hidden items-center gap-2 text-xs text-slate-400 lg:flex"><ShieldCheck class="h-4 w-4 text-emerald-500" />{{ t('admin.trainingConfig.pageHint') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!isLoading" class="mb-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<div v-for="stat in [
|
||||
{ label: t('admin.trainingConfig.stats.total'), value: configs.length, icon: Settings2, tone: 'bg-blue-50 text-blue-600' },
|
||||
{ label: t('admin.trainingConfig.stats.published'), value: publishedCount, icon: CheckCircle2, tone: 'bg-emerald-50 text-emerald-600' },
|
||||
{ label: t('admin.trainingConfig.stats.resources'), value: resourceCount, icon: Library, tone: 'bg-violet-50 text-violet-600' },
|
||||
{ label: t('admin.trainingConfig.stats.levels'), value: configuredLevelCount, icon: Layers3, tone: 'bg-amber-50 text-amber-600' },
|
||||
]" :key="stat.label" class="flex items-center gap-4 rounded-xl border border-slate-200 bg-white px-5 py-4 shadow-sm">
|
||||
<span class="flex h-10 w-10 items-center justify-center rounded-xl" :class="stat.tone"><component :is="stat.icon" class="h-5 w-5" /></span>
|
||||
<div><p class="text-xs font-medium text-muted">{{ stat.label }}</p><p class="mt-1 text-2xl font-bold tracking-tight text-primary">{{ stat.value }}</p></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="isLoading" class="flex items-center justify-center py-24">
|
||||
<div class="h-10 w-10 animate-spin rounded-full border-b-2 border-brand-600" />
|
||||
</div>
|
||||
<div v-else class="grid items-start gap-5 xl:grid-cols-[248px_minmax(0,1fr)]">
|
||||
<aside class="surface-panel overflow-hidden xl:sticky xl:top-6">
|
||||
<div class="border-b border-subtle bg-surface-soft px-4 py-5">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<h2 class="text-sm font-bold text-primary">{{ t('admin.trainingConfig.types') }}</h2>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.typeCount', { count: configs.length }) }}</p>
|
||||
</div>
|
||||
<button class="btn-primary btn-icon" type="button" :title="t('admin.trainingConfig.addType')" @click="openCreate">
|
||||
<Plus class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="space-y-1.5 p-2.5">
|
||||
<div v-if="!configs.length" class="px-3 py-10 text-center text-sm text-slate-500">{{ t('admin.trainingConfig.empty') }}</div>
|
||||
<button v-for="item in configs" :key="item.id" type="button" class="group flex w-full items-center gap-3 rounded-lg border px-3 py-3 text-left transition" :class="item.id === selectedId ? 'border-brand-200 bg-brand-50 text-brand-700 shadow-sm' : 'border-transparent text-secondary hover:border-default hover:bg-surface-soft'" @click="selectConfig(item)">
|
||||
<span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg" :class="item.id === selectedId ? 'bg-surface text-brand-600 shadow-sm' : 'bg-surface-strong text-muted'">
|
||||
<ShieldCheck v-if="item.training_type === 'safety'" class="h-4.5 w-4.5" />
|
||||
<BookOpen v-else class="h-4.5 w-4.5" />
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block truncate text-sm font-semibold">{{ item.name }}</span>
|
||||
<span class="mt-0.5 block truncate text-xs opacity-70">{{ item.training_type }} · {{ item.version }}</span>
|
||||
</span>
|
||||
<ChevronRight class="h-4 w-4 shrink-0 opacity-50 transition group-hover:translate-x-0.5" />
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main v-if="selected" class="min-w-0 space-y-5">
|
||||
<header class="surface-panel px-5 py-5 md:px-7">
|
||||
<div class="flex flex-col gap-5 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div class="flex min-w-0 items-center gap-4">
|
||||
<div class="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-brand-50 text-brand-600">
|
||||
<Settings2 class="h-6 w-6" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2.5">
|
||||
<h2 class="truncate text-xl font-bold tracking-tight text-primary md:text-2xl">{{ form.name }}</h2>
|
||||
<span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-semibold ring-1 ring-inset" :class="statusClass(form.status)">
|
||||
{{ t(`admin.trainingConfig.status.${form.status}`) }}
|
||||
</span>
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm text-slate-500">{{ t('admin.trainingConfig.headerMeta', { type: selected.training_type, version: form.version }) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button class="btn-secondary btn-sm" type="button" @click="editType"><Edit class="h-4 w-4" />{{ t('admin.edit') }}</button>
|
||||
<button class="btn-danger btn-sm" type="button" @click="deleteTarget = selected"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="surface-panel sticky top-2 z-10 flex gap-2 overflow-x-auto p-2" aria-label="Training configuration sections">
|
||||
<button v-for="item in sectionItems" :key="item.id" type="button" class="segment-item shrink-0" :class="activeSection === item.id ? 'segment-item--active' : ''" @click="scrollToSection(item.id)">
|
||||
<component :is="item.icon" class="h-4 w-4" />{{ item.label }}
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<section id="training-section-basic" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex items-start gap-3">
|
||||
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-blue-50 text-blue-600"><Layers3 class="h-5 w-5" /></span>
|
||||
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.basicTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.basicDesc') }}</p></div>
|
||||
</div>
|
||||
<div class="grid gap-x-5 gap-y-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}<input v-model="form.name" class="input-field mt-2" /></label>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.version') }}<input v-model="form.version" class="input-field mt-2" /></label>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.status') }}<select v-model="form.status" class="select-field mt-2"><option value="draft">{{ t('admin.trainingConfig.status.draft') }}</option><option value="published">{{ t('admin.trainingConfig.status.published') }}</option><option value="archived">{{ t('admin.trainingConfig.status.archived') }}</option></select></label>
|
||||
<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>
|
||||
</section>
|
||||
|
||||
<section id="training-section-resources" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-violet-50 text-violet-600"><Library class="h-5 w-5" /></span>
|
||||
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.resourcesTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.resourcesDesc') }}</p></div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!contentResources.length" class="rounded-2xl border border-dashed border-default bg-surface-soft/50 px-5 py-10 text-center">
|
||||
<Library class="mx-auto h-8 w-8 text-muted" />
|
||||
<p class="mt-3 text-sm font-medium text-secondary">{{ t('admin.trainingConfig.resourcesEmpty') }}</p>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmptyHint') }}</p>
|
||||
</div>
|
||||
<div class="flex flex-col gap-5">
|
||||
<article
|
||||
v-for="(level, levelIndex) in trainingLevels"
|
||||
:key="level"
|
||||
class="w-full overflow-hidden rounded-2xl border bg-surface shadow-sm"
|
||||
:class="level === 'company' ? 'border-emerald-200' : level === 'department' ? 'border-blue-200' : 'border-orange-200'"
|
||||
>
|
||||
<div
|
||||
class="flex flex-col gap-4 border-b px-5 py-4 sm:flex-row sm:items-center sm:justify-between"
|
||||
:class="level === 'company' ? 'border-emerald-200 bg-emerald-50/80' : level === 'department' ? 'border-blue-200 bg-blue-50/80' : 'border-orange-200 bg-orange-50/80'"
|
||||
>
|
||||
<div class="flex items-center gap-3">
|
||||
<span
|
||||
class="flex h-10 min-w-10 items-center justify-center rounded-xl px-2 text-sm font-bold text-white shadow-sm"
|
||||
:class="level === 'company' ? 'bg-emerald-500' : level === 'department' ? 'bg-blue-500' : 'bg-orange-500'"
|
||||
>L{{ levelIndex + 1 }}</span>
|
||||
<div>
|
||||
<h4 class="text-base font-bold text-primary">{{ t(`admin.trainingConfig.guideGroups.${level}`) }}</h4>
|
||||
<div class="mt-1 flex items-center gap-1.5 text-xs font-medium text-muted">
|
||||
<Library class="h-3.5 w-3.5" />
|
||||
<span>{{ resourcesByLevel(level).length }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-secondary btn-sm self-start sm:self-auto" type="button" @click="addResource(level)"><Plus class="h-4 w-4" />{{ t('admin.trainingConfig.addResource') }}</button>
|
||||
</div>
|
||||
<div class="p-4 md:p-5">
|
||||
<div v-if="!resourcesByLevel(level).length" class="rounded-xl border border-dashed border-default bg-surface-soft/50 px-3 py-8 text-center text-xs text-muted">{{ t('admin.trainingConfig.resourcesEmpty') }}</div>
|
||||
<div v-else class="space-y-4">
|
||||
<div v-for="(resource, index) in resourcesByLevel(level)" :key="resource.id || `${level}-resource-${index}`" class="rounded-lg border border-default bg-surface p-3 shadow-sm">
|
||||
<div class="grid gap-x-5 gap-y-4 md:grid-cols-2 xl:grid-cols-5">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.resourceKind') }}<select v-model="resource.resource_type" class="select-field mt-2" @change="updateResourceType(resource)"><option value="agent_guide">{{ t('admin.trainingConfig.resourceTypes.guide') }}</option><option value="kb_document_version">{{ t('admin.trainingConfig.resourceTypes.document') }}</option></select></label>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.resourceFile') }}
|
||||
<select v-if="resource.resource_type === 'agent_guide'" v-model.number="resource.agent_guide_id" class="select-field mt-2">
|
||||
<option :value="undefined">{{ t('admin.trainingConfig.selectResource') }}</option>
|
||||
<optgroup v-for="group in guideGroups" :key="group.key" :label="t(`admin.trainingConfig.guideGroups.${group.key}`)">
|
||||
<option v-for="guide in group.items" :key="guide.id" :value="guide.id">{{ guide.file_name }}</option>
|
||||
</optgroup>
|
||||
</select>
|
||||
<select v-else v-model.number="resource.kb_document_version_id" class="select-field mt-2"><option :value="undefined">{{ t('admin.trainingConfig.selectResource') }}</option><option v-for="document in candidates.documents" :key="document.id" :value="document.id">{{ document.file_name }} · v{{ document.version_no }}</option></select>
|
||||
</label>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.resourceTitle') }}<input v-model="resource.title" class="input-field mt-2" :placeholder="t('admin.trainingConfig.resourceTitlePlaceholder')" /></label>
|
||||
<label class="label-field">所需时间(分钟)<input v-model.number="resource.required_duration" type="number" min="0" class="input-field mt-2" placeholder="0表示不限制" /></label>
|
||||
<button class="flex h-10 w-full items-center justify-center gap-2 rounded-xl text-red-500 transition hover:bg-red-50 hover:text-red-600 mt-auto" type="button" :title="t('admin.delete')" @click="removeResource(resource)"><Trash2 class="h-4 w-4" />{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
<div v-if="resource.resource_type === 'agent_guide'" class="mt-3 flex items-center gap-2 text-xs text-muted"><Video class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.guideGroupingHint') }}</div>
|
||||
<div v-else class="mt-3 flex items-center gap-2 text-xs text-muted"><FileText class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.documentVersionHint') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="training-section-exam" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex items-start justify-between gap-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-amber-50 text-amber-600"><FileQuestion class="h-5 w-5" /></span>
|
||||
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.examTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.examDesc') }}</p></div>
|
||||
</div>
|
||||
<span class="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-amber-50 px-3 py-1.5 text-xs font-semibold text-amber-700"><CheckCircle2 class="h-3.5 w-3.5" />{{ t('admin.trainingConfig.questionCount', { count: questionCount }) }}</span>
|
||||
</div>
|
||||
<div class="mb-4 rounded-xl border border-amber-200 bg-amber-50/60 p-4">
|
||||
<div class="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-end">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.questionSource') }}<select v-model.number="questionSourceVersionId" class="select-field mt-2"><option :value="null">{{ t('admin.trainingConfig.selectQuestionSource') }}</option><option v-for="document in candidates.training_exam_documents" :key="document.id" :value="document.id">{{ document.file_name }} · v{{ document.version_no }}</option></select></label>
|
||||
<button class="btn-primary btn-sm" type="button" :disabled="isParsingQuestions || !questionSourceVersionId" @click="parseQuestionBank"><FileQuestion class="h-4 w-4" />{{ isParsingQuestions ? t('admin.trainingConfig.parsingQuestions') : t('admin.trainingConfig.parseQuestions') }}</button>
|
||||
</div>
|
||||
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.questionSourceHint') }}</p>
|
||||
<p v-if="questionParseMeta" class="mt-2 text-xs text-emerald-700">{{ t('admin.trainingConfig.parseStatus', { fileName: questionParseMeta.fileName, mode: questionParseMeta.mode }) }}<span v-if="questionParseMeta.skipped.length">{{ t('admin.trainingConfig.parseSkipped', { numbers: questionParseMeta.skipped.join(', ') }) }}</span></p>
|
||||
</div>
|
||||
<label class="label-field">{{ t('admin.trainingConfig.questionJson') }}<textarea v-model="questionJsonText" class="input-field mt-2 min-h-64 font-mono text-xs leading-5" spellcheck="false" /></label>
|
||||
<p class="mt-2 text-xs text-muted">{{ t('admin.trainingConfig.questionJsonHint') }}</p>
|
||||
</section>
|
||||
|
||||
<section id="training-section-review" class="surface-panel scroll-mt-20 p-5 md:p-7">
|
||||
<div class="mb-6 flex items-start gap-3">
|
||||
<span class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600"><ClipboardCheck class="h-5 w-5" /></span>
|
||||
<div><h3 class="text-base font-bold text-primary">{{ t('admin.trainingConfig.sections.reviewTitle') }}</h3><p class="mt-1 text-sm text-muted">{{ t('admin.trainingConfig.sections.reviewDesc') }}</p></div>
|
||||
</div>
|
||||
|
||||
<template v-if="form.training_type === 'safety'">
|
||||
<div class="mb-5 text-sm font-semibold text-primary">分级培训总结 (按行分隔)</div>
|
||||
<div class="grid gap-5 md:grid-cols-3 mb-8">
|
||||
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-emerald-500" />公司级总结</span><textarea :value="settingSummaryByStageText('company')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('company', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-blue-500" />部门级总结</span><textarea :value="settingSummaryByStageText('department')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('department', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
<label class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-orange-500" />班组级总结</span><textarea :value="settingSummaryByStageText('team')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingSummaryByStageText('team', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="grid gap-5 md:grid-cols-2">
|
||||
<label v-if="form.training_type !== 'safety'" class="label-field"><span class="flex items-center gap-2"><BookOpen class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.summaryPoints') }}</span><textarea :value="settingText('summary_points')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingText('summary_points', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
<label v-if="form.training_type !== 'safety'" class="label-field"><span class="flex items-center gap-2"><ListChecks class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.summaryChecklist') }}</span><textarea :value="settingText('summary_checklist')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.onePerLine')" @input="updateSettingText('summary_checklist', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
<label class="label-field"><span class="flex items-center gap-2"><FileQuestion class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.employeeQuestions') }}</span><textarea :value="settingText('employee_chat_suggested_questions')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.oneQuestionPerLine')" @input="updateSettingText('employee_chat_suggested_questions', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
<label class="label-field"><span class="flex items-center gap-2"><FileQuestion class="h-4 w-4 text-brand-500" />{{ t('admin.trainingConfig.fields.hrQuestions') }}</span><textarea :value="settingText('hr_chat_suggested_questions')" class="input-field mt-2 min-h-32" :placeholder="t('admin.trainingConfig.placeholders.oneQuestionPerLine')" @input="updateSettingText('hr_chat_suggested_questions', ($event.target as HTMLTextAreaElement).value)" /></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="h-16" />
|
||||
</main>
|
||||
<div v-else class="flex min-h-[520px] flex-col items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-400 shadow-sm">
|
||||
<Settings2 class="h-10 w-10" />
|
||||
<p class="mt-4 text-sm">{{ t('admin.trainingConfig.selectHint') }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!isLoading && selected" class="fixed inset-x-0 bottom-0 z-20 border-t border-slate-200 bg-white/95 px-4 py-3 shadow-[0_-8px_24px_rgba(15,23,42,0.08)] backdrop-blur md:left-[var(--sidebar-width,0px)] md:px-8">
|
||||
<div class="mx-auto flex max-w-[1440px] items-center justify-between gap-4">
|
||||
<div class="hidden items-center gap-2 text-xs text-slate-500 sm:flex"><CheckCircle2 class="h-4 w-4 text-emerald-500" />{{ t('admin.trainingConfig.footerHint') }}</div>
|
||||
<div class="ml-auto flex items-center gap-2">
|
||||
<button class="btn-secondary btn-sm" type="button" @click="editType"><Edit class="h-4 w-4" />{{ t('admin.edit') }}</button>
|
||||
<button class="btn-primary min-w-32" type="button" :disabled="isSaving" @click="saveConfig"><Save class="h-4 w-4" />{{ isSaving ? t('admin.trainingConfig.saving') : t('admin.save') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<TrainingTypeFormModal :visible="showTypeEditor" :editing="editingType" :form="typeForm" :is-saving="isSaving" @close="showTypeEditor = false" @save="saveType" />
|
||||
<DeleteConfirmDialog v-model="showDeleteConfirm" :message="t('admin.trainingConfig.confirmDelete')" @confirm="deleteType" />
|
||||
</section>
|
||||
</template>
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
const props = defineProps<{
|
||||
visible: boolean;
|
||||
editing: boolean;
|
||||
form: { training_type: string; name: string };
|
||||
isSaving: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{ close: []; save: [] }>();
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="props.visible" class="admin-modal-overlay animate-fade-in items-center" @click.self="emit('close')">
|
||||
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
|
||||
<div class="px-5 sm:px-8 pt-5 sm:pt-7 pb-4 border-b border-subtle">
|
||||
<h3 class="section-title">{{ props.editing ? t('admin.trainingConfig.editType') : t('admin.trainingConfig.addType') }}</h3>
|
||||
</div>
|
||||
<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>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="label-field">{{ t('admin.trainingConfig.fields.name') }}</label>
|
||||
<input v-model="props.form.name" type="text" class="input-field text-sm" :placeholder="t('admin.trainingConfig.fields.name')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
||||
<button type="button" class="btn-primary disabled:opacity-70" :disabled="props.isSaving" @click="emit('save')">
|
||||
{{ props.isSaving ? `${t('admin.save')}...` : props.editing ? t('admin.update') : t('admin.add') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -20,6 +20,7 @@ export type AdminModuleId =
|
||||
| 'platform_apps'
|
||||
| 'shipping_inventory'
|
||||
| 'procurement_contract'
|
||||
| 'training_config'
|
||||
| 'reports';
|
||||
|
||||
/** 货代管理领域下可由侧栏展示和高亮的稳定业务页面。 */
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* features/admin/types/training-config.types.ts
|
||||
* 用途:约束培训配置管理页、候选资料与三级培训资源的数据结构。
|
||||
* 依赖:admin.api 与 TrainingConfigPage。
|
||||
* 逻辑:管理端按 training_level 保存资料,员工端发布配置沿用同一层级语义。
|
||||
*/
|
||||
export type TrainingConfigStatus = 'draft' | 'published' | 'archived';
|
||||
export type TrainingLevel = 'company' | 'department' | 'team';
|
||||
|
||||
export interface TrainingConfigResource {
|
||||
id?: number;
|
||||
resource_type: 'agent_guide' | 'kb_document_version' | 'inline_questions';
|
||||
training_level?: TrainingLevel | null;
|
||||
title?: string | null;
|
||||
sort_order?: number;
|
||||
required_duration?: number;
|
||||
agent_guide_id?: number;
|
||||
kb_document_version_id?: number;
|
||||
inline_questions?: unknown[];
|
||||
}
|
||||
|
||||
export interface TrainingConfig {
|
||||
id: number;
|
||||
training_type: string;
|
||||
name: string;
|
||||
version: string;
|
||||
status: TrainingConfigStatus;
|
||||
pass_score: number;
|
||||
settings: Record<string, unknown>;
|
||||
resources: TrainingConfigResource[];
|
||||
published_at?: string | null;
|
||||
}
|
||||
|
||||
export interface TrainingConfigPayload {
|
||||
training_type: string;
|
||||
name: string;
|
||||
version: string;
|
||||
status: TrainingConfigStatus;
|
||||
pass_score: number;
|
||||
settings: Record<string, unknown>;
|
||||
resources: TrainingConfigResource[];
|
||||
}
|
||||
|
||||
export interface TrainingResourceCandidates {
|
||||
guides: Array<{
|
||||
id: number;
|
||||
file_name: string;
|
||||
file_type: string;
|
||||
guide_usage: string;
|
||||
file_url?: string;
|
||||
}>;
|
||||
documents: Array<{
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
file_name: string;
|
||||
status: string;
|
||||
group_name: string;
|
||||
}>;
|
||||
training_exam_documents: Array<{
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
file_name: string;
|
||||
status: string;
|
||||
group_name: string;
|
||||
}>;
|
||||
}
|
||||
@@ -6,11 +6,26 @@
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { TrainingAnswerRecord, TrainingProgressRecord, TrainingRecord, TrainingStage, TrainingStats } from '../training/training.types';
|
||||
import type {
|
||||
SafetyProgressState,
|
||||
TrainingAnswerRecord,
|
||||
TrainingExamMode,
|
||||
TrainingProgressRecord,
|
||||
TrainingPublishedConfig,
|
||||
TrainingRecord,
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
TrainingType,
|
||||
} from '../training/training.types';
|
||||
|
||||
type TrainingRecordApi = {
|
||||
id: number;
|
||||
user_id?: number;
|
||||
training_type?: TrainingType;
|
||||
training_version?: string | null;
|
||||
exam_mode?: TrainingExamMode;
|
||||
safety_stage?: string | null;
|
||||
safety_progress?: Partial<SafetyProgressState> | null;
|
||||
employee_id?: string | null;
|
||||
name?: string | null;
|
||||
department?: string | null;
|
||||
@@ -31,6 +46,32 @@ type TrainingRecordApi = {
|
||||
status?: TrainingRecord['status'];
|
||||
};
|
||||
|
||||
type TrainingConfigApi = {
|
||||
id: number;
|
||||
training_type?: TrainingType;
|
||||
version?: string | null;
|
||||
pass_score?: number | null;
|
||||
settings?: Record<string, unknown> | null;
|
||||
resources?: Array<{
|
||||
id?: number | null;
|
||||
resource_type?: string | null;
|
||||
training_level?: 'company' | 'department' | 'team' | null;
|
||||
agent_guide_id?: number | null;
|
||||
inline_questions?: unknown[];
|
||||
title?: string | null;
|
||||
sort_order?: number;
|
||||
required_duration?: number;
|
||||
resource?: {
|
||||
id?: number;
|
||||
file_name?: string;
|
||||
file_type?: string;
|
||||
file_url?: string;
|
||||
guide_usage?: string;
|
||||
source_file_name?: string;
|
||||
} | null;
|
||||
}>;
|
||||
};
|
||||
|
||||
type TrainingListApi = {
|
||||
items: TrainingRecordApi[];
|
||||
total: number;
|
||||
@@ -52,13 +93,19 @@ type TrainingStatsApi = {
|
||||
export interface TrainingRecordQuery {
|
||||
keyword?: string;
|
||||
department?: string;
|
||||
status?: 'all' | 'passed' | 'failed' | 'in_progress';
|
||||
status?: string;
|
||||
type?: string;
|
||||
page?: number;
|
||||
page_size?: number;
|
||||
}
|
||||
|
||||
export interface SaveTrainingProgressPayload {
|
||||
stage: TrainingStage;
|
||||
agentId?: number | null;
|
||||
trainingVersion?: string | null;
|
||||
examMode?: TrainingExamMode;
|
||||
safetyStage?: string | null;
|
||||
safetyProgress?: Partial<SafetyProgressState> | null;
|
||||
currentQuestionIndex: number;
|
||||
score: number;
|
||||
passed: boolean;
|
||||
@@ -80,9 +127,20 @@ function mapAnswerDetails(items?: TrainingRecordApi['answer_details']): Training
|
||||
: [];
|
||||
}
|
||||
|
||||
function mapSafetyProgressState(items?: TrainingRecordApi['safety_progress']): SafetyProgressState {
|
||||
return {
|
||||
company: String(items?.company || 'pending'),
|
||||
department: String(items?.department || 'pending'),
|
||||
team: String(items?.team || 'pending'),
|
||||
resource_progress: (items as any)?.resource_progress || {},
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRecord {
|
||||
return {
|
||||
id: data.id,
|
||||
trainingType: data.training_type || 'onboarding',
|
||||
trainingVersion: data.training_version || undefined,
|
||||
name: String(data.name || ''),
|
||||
employeeId: String(data.employee_id || ''),
|
||||
department: String(data.department || ''),
|
||||
@@ -92,6 +150,9 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
|
||||
attempts: Number(data.attempt_count || 0),
|
||||
status: data.status || 'in_progress',
|
||||
stage: (data.stage || 'video') as TrainingStage,
|
||||
examMode: (data.exam_mode || 'unified') as TrainingExamMode,
|
||||
safetyStage: data.safety_stage ? String(data.safety_stage) as TrainingProgressRecord['safetyStage'] : null,
|
||||
safetyProgress: mapSafetyProgressState(data.safety_progress),
|
||||
currentQuestionIndex: Number(data.current_question_index || 0),
|
||||
passed: Boolean(data.passed),
|
||||
answerDetails: mapAnswerDetails(data.answer_details),
|
||||
@@ -101,10 +162,41 @@ function mapTrainingProgressRecord(data: TrainingRecordApi): TrainingProgressRec
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingConfig(data: TrainingConfigApi): TrainingPublishedConfig {
|
||||
return {
|
||||
id: data.id,
|
||||
trainingType: data.training_type || 'onboarding',
|
||||
version: String(data.version || ''),
|
||||
passScore: Number(data.pass_score || 0),
|
||||
settings: data.settings || {},
|
||||
resources: Array.isArray(data.resources)
|
||||
? data.resources.map((resource) => ({
|
||||
id: resource.id,
|
||||
resourceType: resource.resource_type,
|
||||
trainingLevel: resource.training_level,
|
||||
agentGuideId: resource.agent_guide_id,
|
||||
inlineQuestions: resource.inline_questions,
|
||||
title: resource.title,
|
||||
sortOrder: Number(resource.sort_order || 0),
|
||||
requiredDuration: Number(resource.required_duration || 0),
|
||||
resource: resource.resource ? {
|
||||
id: resource.resource.id,
|
||||
fileName: resource.resource.file_name || resource.resource.source_file_name,
|
||||
fileType: resource.resource.file_type,
|
||||
fileUrl: resource.resource.file_url,
|
||||
guideUsage: resource.resource.guide_usage,
|
||||
} : null,
|
||||
}))
|
||||
: [],
|
||||
};
|
||||
}
|
||||
|
||||
function mapTrainingRecord(data: TrainingRecordApi): TrainingRecord {
|
||||
const progress = mapTrainingProgressRecord(data);
|
||||
return {
|
||||
id: progress.id,
|
||||
trainingType: progress.trainingType,
|
||||
trainingVersion: progress.trainingVersion,
|
||||
name: progress.name,
|
||||
employeeId: progress.employeeId,
|
||||
department: progress.department,
|
||||
@@ -121,26 +213,38 @@ function buildQueryString(query: TrainingRecordQuery = {}) {
|
||||
if (query.keyword) params.set('keyword', query.keyword);
|
||||
if (query.department) params.set('department', query.department);
|
||||
if (query.status) params.set('status', query.status);
|
||||
if (query.type) params.set('type', query.type);
|
||||
if (query.page) params.set('page', String(query.page));
|
||||
if (query.page_size) params.set('page_size', String(query.page_size));
|
||||
return params.toString();
|
||||
}
|
||||
|
||||
export async function getMyTrainingProgress(): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>('/api/user/training-record', authHeaders());
|
||||
export async function getMyTrainingProgress(type: string = 'onboarding'): Promise<TrainingProgressRecord | null> {
|
||||
const data = await requestJson<TrainingRecordApi | null>(`/api/user/training-record?type=${type}`, authHeaders());
|
||||
return data ? mapTrainingProgressRecord(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload): Promise<TrainingProgressRecord> {
|
||||
export async function getMyTrainingConfig(type: string = 'onboarding'): Promise<TrainingPublishedConfig | null> {
|
||||
const data = await requestJson<TrainingConfigApi | null>(`/api/user/training-config?type=${encodeURIComponent(type)}`, authHeaders());
|
||||
return data ? mapTrainingConfig(data) : null;
|
||||
}
|
||||
|
||||
export async function saveMyTrainingProgress(payload: SaveTrainingProgressPayload, type: string = 'onboarding'): Promise<TrainingProgressRecord> {
|
||||
const data = await requestJson<TrainingRecordApi>('/api/user/training-record/progress', {
|
||||
method: 'PUT',
|
||||
...jsonAuthHeaders(),
|
||||
body: JSON.stringify({
|
||||
agent_id: payload.agentId || undefined,
|
||||
stage: payload.stage,
|
||||
training_version: payload.trainingVersion || undefined,
|
||||
exam_mode: payload.examMode || undefined,
|
||||
safety_stage: payload.safetyStage || undefined,
|
||||
safety_progress: payload.safetyProgress || undefined,
|
||||
current_question_index: payload.currentQuestionIndex,
|
||||
score: payload.score,
|
||||
passed: payload.passed,
|
||||
attempt_count: payload.attemptCount,
|
||||
type: type,
|
||||
answer_details: payload.answerDetails.map((item) => ({
|
||||
question_id: item.questionId,
|
||||
selected_option_id: item.selectedOptionId,
|
||||
|
||||
@@ -20,11 +20,19 @@ import {
|
||||
RefreshCcw,
|
||||
ShieldCheck,
|
||||
Target,
|
||||
User,
|
||||
FileText,
|
||||
Video,
|
||||
Lock,
|
||||
XCircle,
|
||||
} from 'lucide-vue-next';
|
||||
import { useTrainingWorkspace } from '@/features/chat/composables/useTrainingWorkspace';
|
||||
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { resolveTrainingExamPdfGuide, type TrainingGuideLike } from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
const props = defineProps<{
|
||||
currentAgent: Record<string, unknown> | null;
|
||||
currentUser: Record<string, unknown> | null;
|
||||
@@ -39,9 +47,13 @@ const emit = defineEmits<{
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const msg = useMessage();
|
||||
|
||||
const workspace = reactive(props.training);
|
||||
|
||||
const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null);
|
||||
const showFilePreview = ref(false);
|
||||
|
||||
// 将 workspace 内部控制弹窗的状态同步给组件本地变量(如果需要,或者直接用 workspace.showVideoModal)
|
||||
const showVideoModal = computed({
|
||||
get: () => workspace.showVideoModal,
|
||||
@@ -82,14 +94,14 @@ const handleVideoSeeking = (e: Event) => {
|
||||
};
|
||||
|
||||
const handleVideoEnded = () => {
|
||||
showVideoModal.value = false;
|
||||
workspace.markVideoCompleted();
|
||||
workspace.showVideoModal = false;
|
||||
workspace.stopMaterialTimer();
|
||||
};
|
||||
|
||||
const reportVideoDebugEvent = (event: Event) => {
|
||||
const video = event.target as HTMLVideoElement;
|
||||
// #region debug-point A-E:ios-video-runtime
|
||||
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
|
||||
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || currentPreviewVideoUrl.value || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
|
||||
// #endregion
|
||||
};
|
||||
|
||||
@@ -227,6 +239,50 @@ const examQuestionItems = computed(() => Array.from({ length: workspace.totalQue
|
||||
};
|
||||
}));
|
||||
const canNavigateExamQuestions = computed(() => workspace.stage === 'exam');
|
||||
const isMaterialCompleted = (material: any) => {
|
||||
const resourceProgress = workspace.safetyProgress.resource_progress || {};
|
||||
const record = resourceProgress[material.id];
|
||||
return record ? !!record.completed : false;
|
||||
};
|
||||
|
||||
const currentPreviewVideoUrl = ref('');
|
||||
|
||||
const handleMaterialClick = (material: any) => {
|
||||
const url = material.resource?.fileUrl;
|
||||
if (!url) {
|
||||
msg.warning('该资料暂无可预览的文件');
|
||||
return;
|
||||
}
|
||||
|
||||
if (material.resource?.fileType === 'video') {
|
||||
workspace.showVideoModal = true;
|
||||
currentPreviewVideoUrl.value = url;
|
||||
// 当点击视频资料时,我们应该记录正在观看的资源ID,以便后续更新进度
|
||||
workspace.currentViewingMaterialId = material.id;
|
||||
} else {
|
||||
previewFile.value = {
|
||||
name: material.title || material.resource?.fileName || '资料预览',
|
||||
url: url,
|
||||
actualExt: material.resource?.fileType,
|
||||
};
|
||||
showFilePreview.value = true;
|
||||
workspace.currentViewingMaterialId = material.id;
|
||||
}
|
||||
workspace.startMaterialTimer(material.id);
|
||||
};
|
||||
|
||||
const handlePreviewClose = (val: boolean) => {
|
||||
showFilePreview.value = val;
|
||||
if (!val) {
|
||||
workspace.stopMaterialTimer();
|
||||
}
|
||||
};
|
||||
|
||||
const handleVideoModalClose = () => {
|
||||
workspace.showVideoModal = false;
|
||||
currentPreviewVideoUrl.value = '';
|
||||
workspace.stopMaterialTimer();
|
||||
};
|
||||
const jumpToExamQuestion = (index: number) => {
|
||||
if (!canNavigateExamQuestions.value) return;
|
||||
workspace.syncExamQuestionIndex(index);
|
||||
@@ -239,6 +295,21 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
if (!canSwitchToStage(stageKey)) return;
|
||||
workspace.stage = stageKey as typeof workspace.stage;
|
||||
};
|
||||
|
||||
// --- 安全培训相关计算属性 ---
|
||||
const safetySteps = computed(() => workspace.safetyStepItems);
|
||||
|
||||
const currentSafetySummary = computed(() => {
|
||||
return workspace.publishedSafetySummary;
|
||||
});
|
||||
|
||||
const currentSafetyStageText = computed(() => {
|
||||
if (workspace.safetyViewStage === 'company') return t('chat.training.safety.steps.company');
|
||||
if (workspace.safetyViewStage === 'department') return t('chat.training.safety.steps.department');
|
||||
if (workspace.safetyViewStage === 'team') return t('chat.training.safety.steps.team');
|
||||
if (workspace.safetyViewStage === 'exam') return t('chat.training.safety.steps.exam');
|
||||
return t('chat.training.steps.result');
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -412,7 +483,38 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
</div>
|
||||
|
||||
<div v-if="!isCompactMode && workspace.activeView === 'learner'" :class="learnerWorkspaceGridClass">
|
||||
<div :class="learnerWorkspaceMainClass">
|
||||
<!-- 增加顶部 Tab 切换:入职培训 / 安全培训 -->
|
||||
<div class="col-span-full mb-1">
|
||||
<div class="inline-flex rounded-xl border border-default bg-surface-soft p-1">
|
||||
<button
|
||||
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'"
|
||||
>
|
||||
<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') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="workspace.trainingConfigLoading" class="col-span-full rounded-2xl border border-default bg-white px-6 py-16 text-center text-secondary">
|
||||
{{ $t('chat.training.noContent.loading') }}
|
||||
</div>
|
||||
<div v-else-if="!workspace.hasPublishedTrainingConfig" class="col-span-full rounded-2xl border border-dashed border-brand-200 bg-white px-6 py-16 text-center text-secondary">
|
||||
<FileText class="mx-auto h-10 w-10 text-brand-300" />
|
||||
<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'">
|
||||
<div :class="learnerWorkspaceMainClass">
|
||||
<div :class="progressCardClass">
|
||||
<div class="flex flex-col gap-1.5 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div>
|
||||
@@ -666,8 +768,39 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 md:sticky md:top-3 md:self-start">
|
||||
<div :class="questionNavPanelClass">
|
||||
<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 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"
|
||||
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' :
|
||||
'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'"
|
||||
>
|
||||
<CheckCircle2 v-if="stageStep > index + 1" class="h-4 w-4" />
|
||||
<span v-else class="text-xs font-bold">{{ index + 1 }}</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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 考试题目面板 (在考试或结果阶段展示) -->
|
||||
<div v-else :class="questionNavPanelClass">
|
||||
<div class="flex items-center gap-2">
|
||||
<ClipboardCheck class="h-4 w-4 text-brand-600" />
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
|
||||
@@ -709,6 +842,335 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 安全培训视图 -->
|
||||
<template v-else>
|
||||
<div :class="learnerWorkspaceMainClass">
|
||||
<!-- 进度卡片 -->
|
||||
<div :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.safety.progressTitle') }}
|
||||
</div>
|
||||
<div class="mt-0.5 text-[11px] leading-4.5 text-secondary md:text-xs">
|
||||
{{ $t('chat.training.safety.progressHint') }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft px-2.5 py-1 text-center">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.progressPercent') }}</div>
|
||||
<div class="text-base font-semibold leading-none text-primary">{{ workspace.safetyProgressPercent }}%</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2 grid grid-cols-2 gap-1 lg:grid-cols-4">
|
||||
<div
|
||||
v-for="step in safetySteps"
|
||||
:key="step.id"
|
||||
class="cursor-pointer rounded-xl border px-2 py-1.5 transition"
|
||||
:class="[
|
||||
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50' :
|
||||
step.status === 'active' ? 'border-brand-500 bg-brand-500 text-white shadow-sm' :
|
||||
'border-default bg-surface-soft/70 opacity-60'
|
||||
]"
|
||||
@click="step.status !== 'locked' ? workspace.setSafetyStage(step.id as any) : null"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<div
|
||||
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full"
|
||||
:class="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-white text-brand-600' : 'bg-white text-muted'"
|
||||
>
|
||||
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
|
||||
<PlayCircle v-else-if="step.id !== 'exam'" class="h-4 w-4" />
|
||||
<Lock v-else-if="step.status === 'locked'" class="h-3 w-3" />
|
||||
<ClipboardCheck v-else class="h-4 w-4" />
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<div class="whitespace-normal text-[12px] font-medium leading-4" :class="step.status === 'active' ? 'text-white' : 'text-primary'">{{ step.label }}</div>
|
||||
<div class="text-[10px] font-medium mt-0.5" :class="step.status === 'active' ? 'text-white/80' : 'text-secondary'">
|
||||
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
|
||||
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
|
||||
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
|
||||
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主内容区 -->
|
||||
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== 'result'" class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex justify-between items-center">
|
||||
<div>
|
||||
<span class="inline-flex rounded-md bg-amber-500 px-2 py-0.5 text-xs font-semibold text-white">
|
||||
{{ currentSafetyStageText }}
|
||||
</span>
|
||||
<span class="ml-2 text-base font-semibold text-primary">{{ $t('chat.training.safety.videoPanelSubtitle') }}</span>
|
||||
</div>
|
||||
<div class="text-xs font-medium text-amber-500">
|
||||
{{ $t('chat.training.safety.videoPanelPassLine') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4">
|
||||
<div class="text-sm font-semibold text-primary mb-3">{{ $t('chat.training.safety.materialsTitle') }}</div>
|
||||
<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 hover:bg-slate-100 transition" @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.safety.materials.m2') }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-end gap-1">
|
||||
<span class="text-xs text-secondary">{{ currentSafetyStageText }}</span>
|
||||
<span v-if="material.requiredDuration" class="text-xs font-semibold" :class="isMaterialCompleted(material) ? 'text-emerald-500' : 'text-amber-500'">所需时间: {{ material.requiredDuration }} 分钟 ({{ isMaterialCompleted(material) ? '已完成' : '未完成' }})</span>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="workspace.safetyViewStage === 'exam' && workspace.currentQuestion" :class="examPanelClass">
|
||||
<div class="flex flex-col gap-2.5 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-brand-600">
|
||||
{{ $t('chat.training.safety.steps.exam') }}
|
||||
</div>
|
||||
<h3 class="mt-1 text-base font-semibold text-primary md:text-lg">
|
||||
{{ $t('chat.training.exam.questionCounter', { current: workspace.currentQuestionNumber, total: workspace.totalQuestionCount }) }}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="flex flex-wrap gap-1.5 text-xs text-secondary md:text-sm">
|
||||
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
|
||||
{{ $t('chat.training.exam.currentScore', { score: workspace.score }) }}
|
||||
</div>
|
||||
<div class="rounded-xl bg-surface-soft px-2.5 py-1.5">
|
||||
{{ $t('chat.training.exam.passLine', { passScore: workspace.passScore }) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 rounded-2xl border border-brand-100 bg-brand-50/40 p-3">
|
||||
<div class="text-[15px] font-semibold leading-6 text-primary md:text-base">
|
||||
{{ workspace.currentQuestion.prompt }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-2.5 grid gap-2">
|
||||
<button
|
||||
v-for="option in workspace.currentQuestion.options"
|
||||
:key="option.id"
|
||||
type="button"
|
||||
class="rounded-2xl border px-3.5 py-2 text-left text-sm leading-5 transition"
|
||||
:class="[
|
||||
workspace.selectedOptionId === option.id
|
||||
? workspace.answerLocked
|
||||
? option.id === workspace.currentQuestion.answer
|
||||
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
|
||||
: 'border-red-300 bg-red-50 text-red-700'
|
||||
: 'border-brand-300 bg-brand-50 text-brand-700'
|
||||
: workspace.answerLocked && option.id === workspace.currentQuestion.answer
|
||||
? 'border-emerald-300 bg-emerald-50 text-emerald-700'
|
||||
: 'border-default bg-white text-secondary hover:border-brand-200 hover:bg-brand-50/40',
|
||||
]"
|
||||
@click="workspace.selectAnswer(option.id)"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<span>{{ option.label }}</span>
|
||||
<CheckCircle2
|
||||
v-if="workspace.answerLocked && option.id === workspace.currentQuestion.answer"
|
||||
class="mt-0.5 h-4 w-4 shrink-0 text-emerald-500"
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="workspace.answerLocked"
|
||||
class="mt-3 rounded-2xl border p-3"
|
||||
:class="workspace.currentFeedbackCorrect ? 'border-emerald-200 bg-emerald-50/70' : 'border-red-200 bg-red-50/70'"
|
||||
>
|
||||
<div class="flex items-center gap-2 text-sm font-semibold" :class="workspace.currentFeedbackCorrect ? 'text-emerald-700' : 'text-red-700'">
|
||||
<CheckCircle2 v-if="workspace.currentFeedbackCorrect" class="h-4 w-4" />
|
||||
<XCircle v-else class="h-4 w-4" />
|
||||
{{ workspace.currentFeedbackCorrect ? $t('chat.training.exam.correctFeedback') : $t('chat.training.exam.wrongFeedback') }}
|
||||
</div>
|
||||
<div class="mt-2 text-sm leading-6 text-secondary">
|
||||
{{ $t('chat.training.exam.selectedAnswer', { answer: currentAnswerLabel || '--' }) }}
|
||||
</div>
|
||||
<div class="mt-1 text-sm leading-6 text-secondary">
|
||||
{{ $t('chat.training.exam.correctAnswer', { answer: workspace.currentQuestion.options?.find((item) => item.id === workspace.currentQuestion?.answer)?.label || '--' }) }}
|
||||
</div>
|
||||
<div class="mt-2 text-sm leading-6 text-secondary">
|
||||
{{ workspace.currentQuestion.explanation }}
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.examReadyToSubmit ? workspace.submitExam() : workspace.moveToNextQuestion()"
|
||||
>
|
||||
<ClipboardCheck class="h-4 w-4" />
|
||||
{{
|
||||
workspace.examReadyToSubmit
|
||||
? $t('chat.training.exam.submitPaper')
|
||||
: $t('chat.training.exam.nextQuestion')
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<div>
|
||||
<div class="inline-flex items-center gap-2 rounded-full px-3 py-1 text-xs font-semibold"
|
||||
:class="workspace.isPassed ? 'bg-emerald-50 text-emerald-700' : 'bg-amber-50 text-amber-700'"
|
||||
>
|
||||
<ShieldCheck class="h-3.5 w-3.5" />
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passedTag') : $t('chat.training.result.failedTag') }}
|
||||
</div>
|
||||
<h3 class="mt-2.5 text-lg font-semibold text-primary md:text-xl">
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passTitle') : $t('chat.training.result.failTitle') }}
|
||||
</h3>
|
||||
<p class="mt-2 text-sm leading-6 text-secondary">
|
||||
{{ workspace.isPassed ? $t('chat.training.result.passDescription') : $t('chat.training.result.failDescription', { passScore: workspace.passScore }) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 gap-2 text-center">
|
||||
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.result.scoreLabel') }}</div>
|
||||
<div class="text-xl font-semibold text-primary">{{ workspace.score }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl bg-surface-soft px-4 py-2.5">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.result.attemptsLabel') }}</div>
|
||||
<div class="text-xl font-semibold text-primary">{{ workspace.attemptCount }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-2.5 md:grid-cols-3">
|
||||
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.result.correctCount') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.correctCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.result.wrongCount') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.wrongCount }}</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft p-3.5">
|
||||
<div class="text-xs text-muted">{{ $t('chat.training.result.completionDate') }}</div>
|
||||
<div class="mt-1 text-lg font-semibold text-primary">{{ workspace.completionDate || '--' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-2.5">
|
||||
<button
|
||||
v-if="!workspace.isPassed"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-2 rounded-xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition hover:bg-brand-700"
|
||||
@click="workspace.restartExam"
|
||||
>
|
||||
<RefreshCcw class="h-4 w-4" />
|
||||
{{ $t('chat.training.result.retryExam') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 md:sticky md:top-3 md:self-start space-y-4">
|
||||
<!-- 流程进度面板 (仅在非考试阶段展示) -->
|
||||
<div v-if="workspace.safetyViewStage !== 'exam' && workspace.safetyViewStage !== '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.safety.progressTitle') }}</div>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-for="(step, index) in safetySteps"
|
||||
:key="step.id"
|
||||
class="flex items-center gap-3 p-2 rounded-lg border transition"
|
||||
:class="[
|
||||
step.status === 'completed' ? 'border-emerald-200 bg-emerald-50/50' :
|
||||
step.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="step.status === 'completed' ? 'bg-emerald-500 text-white' : step.status === 'active' ? 'bg-brand-500 text-white shadow-sm' : 'bg-slate-200 text-slate-400'"
|
||||
>
|
||||
<CheckCircle2 v-if="step.status === 'completed'" class="h-4 w-4" />
|
||||
<span v-else class="text-xs font-bold">{{ index + 1 }}</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="text-xs font-semibold" :class="step.status === 'active' ? 'text-brand-700' : 'text-slate-700'">{{ step.label }}</div>
|
||||
<div class="text-[10px] text-slate-500 mt-0.5">
|
||||
<span v-if="step.status === 'completed'">{{ $t('chat.training.safety.stepStatus.completed') }}</span>
|
||||
<span v-else-if="step.status === 'active' && step.id !== 'exam'">{{ $t('chat.training.safety.stepStatus.watchVideo') }}</span>
|
||||
<span v-else-if="step.id === 'exam'">{{ $t('chat.training.safety.stepStatus.examReq') }}</span>
|
||||
<span v-else>{{ $t('chat.training.safety.stepStatus.pending') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 考试题目面板 (在考试阶段或结果阶段展示) -->
|
||||
<div v-else :class="questionNavPanelClass">
|
||||
<div class="flex items-center gap-2">
|
||||
<ClipboardCheck class="h-4 w-4 text-brand-600" />
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.examQuestionCard.title') }}</div>
|
||||
</div>
|
||||
<div class="mt-1.5 text-[11px] leading-4.5 text-secondary">
|
||||
{{ $t('chat.training.examQuestionCard.hint') }}
|
||||
</div>
|
||||
<div :class="questionNavGridClass">
|
||||
<button
|
||||
v-for="item in examQuestionItems"
|
||||
:key="item.index"
|
||||
type="button"
|
||||
:class="[
|
||||
questionNavButtonClass,
|
||||
item.status === 'active'
|
||||
? 'border-brand-500 bg-brand-600 text-white shadow-sm'
|
||||
: item.status === 'correct'
|
||||
? 'border-emerald-200 bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
|
||||
: item.status === 'wrong'
|
||||
? 'border-red-200 bg-red-50 text-red-700 hover:bg-red-100'
|
||||
: 'border-default bg-surface-soft text-muted hover:border-slate-300 hover:bg-slate-100',
|
||||
!canNavigateExamQuestions ? 'cursor-not-allowed opacity-80' : '',
|
||||
]"
|
||||
:disabled="!canNavigateExamQuestions"
|
||||
@click="jumpToExamQuestion(item.index)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="my-2.5 h-px bg-slate-100" />
|
||||
<div class="text-sm font-semibold text-primary">{{ $t('chat.training.rules.title') }}</div>
|
||||
<ul class="mt-1.5 grid gap-1 text-[11px] leading-4.5 text-secondary">
|
||||
<li v-for="rule in ruleItems" :key="rule" class="flex gap-2">
|
||||
<CheckCircle2 class="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500" />
|
||||
<span>{{ rule }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<!-- 培训总结 -->
|
||||
<div v-if="currentSafetySummary && currentSafetySummary.length > 0" :class="questionNavPanelClass" class="bg-amber-50/50 border-amber-100">
|
||||
<div class="text-sm font-semibold text-amber-900 mb-2">{{ $t('chat.training.safety.summaryTitle') }}</div>
|
||||
<ul class="space-y-1.5 text-[11px] leading-4.5 text-amber-800/80">
|
||||
<li v-for="(point, idx) in currentSafetySummary" :key="idx" class="flex gap-1.5">
|
||||
<span class="mt-1.5 h-1 w-1 shrink-0 rounded-full bg-amber-400"></span>
|
||||
<span>{{ point }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!isCompactMode" class="space-y-4 p-4 md:p-5">
|
||||
@@ -747,7 +1209,7 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
|
||||
<div class="rounded-2xl border border-default bg-white p-4 shadow-sm">
|
||||
<div class="flex flex-col gap-3">
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
|
||||
<div class="grid gap-3 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_auto] xl:items-center">
|
||||
<label>
|
||||
<input
|
||||
v-model="workspace.hrKeyword"
|
||||
@@ -756,6 +1218,16 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
:placeholder="$t('chat.training.hr.filters.keywordPlaceholder')"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrTypeFilter"
|
||||
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>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<select
|
||||
v-model="workspace.hrStatusFilter"
|
||||
@@ -840,9 +1312,9 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
</section>
|
||||
|
||||
<Teleport to="body">
|
||||
<div v-if="showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="showVideoModal = false">
|
||||
<div v-if="workspace.showVideoModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-slate-950/80 p-4 backdrop-blur-sm" @click.self="handleVideoModalClose">
|
||||
<div class="relative w-full max-w-4xl overflow-hidden rounded-3xl bg-black shadow-2xl">
|
||||
<button @click="showVideoModal = false" class="absolute top-4 right-4 z-10 h-10 w-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition backdrop-blur-md">
|
||||
<button @click="handleVideoModalClose" class="absolute top-4 right-4 z-10 h-10 w-10 flex items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/20 transition backdrop-blur-md">
|
||||
<XCircle class="h-6 w-6" />
|
||||
</button>
|
||||
<div class="aspect-video bg-black">
|
||||
@@ -863,11 +1335,18 @@ const handleStageCardClick = (stageKey: string) => {
|
||||
@seeking="handleVideoSeeking"
|
||||
@ended="handleVideoEnded"
|
||||
>
|
||||
<source :src="workspace.videoUrl" type="video/mp4">
|
||||
<source :src="currentPreviewVideoUrl || workspace.videoUrl" type="video/mp4">
|
||||
Your browser does not support the video tag.
|
||||
</video>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FilePreviewModal
|
||||
v-model="showFilePreview"
|
||||
:file="previewFile"
|
||||
:agent-id="workspace.currentTrainingAgentId || undefined"
|
||||
:auth-headers="getAuthHeaders()"
|
||||
@update:modelValue="handlePreviewClose"
|
||||
/>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -10,33 +10,40 @@ import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
exportTrainingRecords,
|
||||
getMyTrainingConfig,
|
||||
getMyTrainingProgress,
|
||||
getTrainingStats,
|
||||
listTrainingRecords,
|
||||
saveMyTrainingProgress,
|
||||
} from '@/features/chat/api/training.api';
|
||||
import type {
|
||||
SafetyProgressState,
|
||||
TrainingAnswerRecord,
|
||||
TrainingContentConfig,
|
||||
TrainingExamMode,
|
||||
TrainingExamTransitionFeedback,
|
||||
TrainingQuestion,
|
||||
TrainingQuestionOption,
|
||||
TrainingProgressRecord,
|
||||
TrainingPublishedConfig,
|
||||
TrainingRecord,
|
||||
TrainingRecordStatus,
|
||||
SafetyStage,
|
||||
TrainingStage,
|
||||
TrainingStats,
|
||||
TrainingType,
|
||||
TrainingWorkspaceView,
|
||||
} from '@/features/chat/training/training.types';
|
||||
import {
|
||||
SAFETY_STAGE_GUIDE_USAGE_MAP,
|
||||
matchesTrainingAgent,
|
||||
resolveTrainingContentConfig,
|
||||
resolveTrainingVideoGuide,
|
||||
resolveTrainingVideoUrl,
|
||||
resolveSafetyTrainingVideoGuide,
|
||||
type TrainingGuideLike,
|
||||
} from '@/features/chat/training/trainingWorkspace.utils';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
id?: number | null;
|
||||
name?: string | null;
|
||||
extra_config?: Record<string, unknown> | null;
|
||||
} | null | undefined;
|
||||
@@ -52,14 +59,19 @@ type TrainingUserLike = {
|
||||
} | null;
|
||||
} | null | undefined;
|
||||
|
||||
type SafetyLearningStage = Exclude<SafetyStage, 'exam' | 'result'>;
|
||||
|
||||
export interface UseTrainingWorkspaceOptions {
|
||||
currentAgent: ComputedRef<TrainingAgentLike>;
|
||||
currentUser: ComputedRef<TrainingUserLike>;
|
||||
currentGuides: ComputedRef<TrainingGuideLike[]>;
|
||||
}
|
||||
|
||||
const DEFAULT_TRAINING_VIDEO_URL = 'https://www.w3schools.com/html/mov_bbb.mp4';
|
||||
const DEFAULT_PASS_SCORE = 90;
|
||||
const DEFAULT_TRAINING_VERSION: Record<TrainingType, string> = {
|
||||
onboarding: 'onboarding-v1',
|
||||
safety: 'safety-v1',
|
||||
};
|
||||
|
||||
const formatDate = (value: Date) => value.toISOString().slice(0, 10);
|
||||
|
||||
@@ -78,10 +90,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const msg = useMessage();
|
||||
|
||||
const isTrainingAgent = computed(() => matchesTrainingAgent(currentAgent.value));
|
||||
const currentTrainingAgentId = computed<number | null>(() => {
|
||||
const parsed = Number(currentAgent.value?.id);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
||||
});
|
||||
const hasAuthenticatedUser = computed(() => Boolean(String(currentUser.value?.username || '').trim()));
|
||||
const isAdminViewer = computed(() => Boolean(currentUser.value?.feature_permissions?.training_hr_manage));
|
||||
const 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 examMode = ref<TrainingExamMode>('unified');
|
||||
const safetyStage = ref<SafetyStage>('company');
|
||||
const safetyViewStage = ref<SafetyStage>('company');
|
||||
const safetyProgress = ref<SafetyProgressState>({
|
||||
company: 'active',
|
||||
department: 'pending',
|
||||
team: 'pending',
|
||||
});
|
||||
|
||||
const stage = ref<TrainingStage>('video');
|
||||
const currentQuestionIndex = ref(0);
|
||||
@@ -103,10 +129,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const isHydrated = ref(false);
|
||||
const hasWarnedPersistFailure = ref(false);
|
||||
const hasWarnedLoadFailure = ref(false);
|
||||
const publishedConfig = ref<TrainingPublishedConfig | null>(null);
|
||||
const trainingConfigLoading = ref(false);
|
||||
|
||||
const hrKeyword = ref('');
|
||||
const hrStatusFilter = ref<'all' | TrainingRecordStatus>('all');
|
||||
const hrDepartmentFilter = ref('all');
|
||||
const hrTypeFilter = ref('all');
|
||||
const records = ref<TrainingRecord[]>([]);
|
||||
const departmentOptions = ref<string[]>([]);
|
||||
const stats = ref<TrainingStats>({
|
||||
@@ -190,12 +219,42 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
questionBank: defaultQuestionBank.value,
|
||||
},
|
||||
booleanOptions.value,
|
||||
publishedConfig.value,
|
||||
));
|
||||
|
||||
const summaryPoints = computed(() => trainingContent.value.summaryPoints);
|
||||
const summaryChecklist = computed(() => trainingContent.value.summaryChecklist);
|
||||
const questionBank = computed<TrainingQuestion[]>(() => trainingContent.value.questionBank);
|
||||
const passScore = computed(() => trainingContent.value.passScore);
|
||||
const hasPublishedTrainingConfig = computed(() => publishedConfig.value !== null);
|
||||
const activeSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
|
||||
['company', 'department', 'team'].includes(safetyStage.value)
|
||||
? safetyStage.value as SafetyLearningStage
|
||||
: null
|
||||
));
|
||||
const visibleSafetyLearningStage = computed<SafetyLearningStage | null>(() => (
|
||||
['company', 'department', 'team'].includes(safetyViewStage.value)
|
||||
? safetyViewStage.value as SafetyLearningStage
|
||||
: null
|
||||
));
|
||||
const resolveSafetyStageMaterials = (targetStage: SafetyLearningStage | null) => [...(publishedConfig.value?.resources || [])]
|
||||
.filter((resource) => resource.resourceType !== 'inline_questions')
|
||||
.filter((resource) => !targetStage || resource.trainingLevel === targetStage)
|
||||
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0));
|
||||
/**
|
||||
* 按当前安全培训阶段筛选已发布资料。
|
||||
* AI 触发时机:员工进入公司级、部门级或班组级页面时,只展示后台绑定到当前级别的资料;入职培训仍展示全部非题库资料。
|
||||
*/
|
||||
const publishedTrainingMaterials = computed(() => [...(publishedConfig.value?.resources || [])]
|
||||
.filter((resource) => resource.resourceType !== 'inline_questions')
|
||||
.filter((resource) => learnerTab.value !== 'safety' || resource.trainingLevel === visibleSafetyLearningStage.value)
|
||||
.sort((left, right) => Number(left.sortOrder || 0) - Number(right.sortOrder || 0)));
|
||||
const publishedSafetySummary = computed(() => {
|
||||
const summaries = publishedConfig.value?.settings?.summaryByStage;
|
||||
if (!summaries || typeof summaries !== 'object') return [];
|
||||
const value = (summaries as Record<string, unknown>)[safetyViewStage.value];
|
||||
return Array.isArray(value) ? value.map((item) => String(item)) : [];
|
||||
});
|
||||
|
||||
const currentQuestion = computed(() => questionBank.value[currentQuestionIndex.value] || null);
|
||||
const totalQuestionCount = computed(() => questionBank.value.length);
|
||||
@@ -213,8 +272,55 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
&& answeredCount.value >= totalQuestionCount.value
|
||||
));
|
||||
const canEnterResultStage = computed(() => stage.value === 'result');
|
||||
const safetyProgressPercent = computed(() => {
|
||||
if (safetyStage.value === 'company') return 25;
|
||||
if (safetyStage.value === 'department') return 50;
|
||||
if (safetyStage.value === 'team') return 75;
|
||||
if (safetyStage.value === 'exam') return 90;
|
||||
return 100;
|
||||
});
|
||||
const safetyStepItems = computed(() => {
|
||||
const base: Array<{ id: SafetyStage extends infer U ? U : never; labelKey: string }> = [
|
||||
{ id: 'company', labelKey: 'chat.training.safety.steps.company' },
|
||||
{ id: 'department', labelKey: 'chat.training.safety.steps.department' },
|
||||
{ id: 'team', labelKey: 'chat.training.safety.steps.team' },
|
||||
{ id: 'exam', labelKey: 'chat.training.safety.steps.exam' },
|
||||
];
|
||||
return base.map((item) => {
|
||||
let status: 'completed' | 'active' | 'pending' | 'locked' = 'pending';
|
||||
if (item.id === 'company') {
|
||||
status = safetyProgress.value.company === 'completed'
|
||||
? 'completed'
|
||||
: safetyProgress.value.company === 'active' ? 'active' : 'pending';
|
||||
} else if (item.id === 'department') {
|
||||
status = safetyProgress.value.department === 'completed'
|
||||
? 'completed'
|
||||
: safetyProgress.value.department === 'active' ? 'active' : 'pending';
|
||||
} else if (item.id === 'team') {
|
||||
status = safetyProgress.value.team === 'completed'
|
||||
? 'completed'
|
||||
: safetyProgress.value.team === 'active' ? 'active' : 'pending';
|
||||
} else if (item.id === 'exam') {
|
||||
status = ['exam', 'result'].includes(safetyStage.value)
|
||||
? (safetyStage.value === 'exam' ? 'active' : 'completed')
|
||||
: (safetyProgress.value.company === 'completed'
|
||||
&& safetyProgress.value.department === 'completed'
|
||||
&& safetyProgress.value.team === 'completed'
|
||||
? 'pending'
|
||||
: 'locked');
|
||||
}
|
||||
return {
|
||||
id: item.id,
|
||||
label: t(item.labelKey),
|
||||
status,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const learnerProgressPercent = computed(() => {
|
||||
if (learnerTab.value === 'safety') {
|
||||
return safetyProgressPercent.value;
|
||||
}
|
||||
if (stage.value === 'video') return 25;
|
||||
if (stage.value === 'summary') return 50;
|
||||
if (stage.value === 'result') return 100;
|
||||
@@ -353,14 +459,69 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
/**
|
||||
* 按安全培训目标阶段重置三级学习进度。
|
||||
* AI 触发时机:当员工完成上一级学习、切换安全培训阶段,或后端恢复安全培训初始态时,需要一次性得到完整的三级状态快照。
|
||||
*/
|
||||
const resetSafetyProgress = (nextStage: SafetyStage = 'company') => {
|
||||
const resourceProgressSnapshot = safetyProgress.value.resource_progress
|
||||
? { ...safetyProgress.value.resource_progress }
|
||||
: undefined;
|
||||
safetyStage.value = nextStage;
|
||||
safetyViewStage.value = nextStage;
|
||||
if (nextStage === 'company') {
|
||||
safetyProgress.value = { company: 'active', department: 'pending', team: 'pending', resource_progress: resourceProgressSnapshot };
|
||||
return;
|
||||
}
|
||||
if (nextStage === 'department') {
|
||||
safetyProgress.value = { company: 'completed', department: 'active', team: 'pending', resource_progress: resourceProgressSnapshot };
|
||||
return;
|
||||
}
|
||||
if (nextStage === 'team') {
|
||||
safetyProgress.value = { company: 'completed', department: 'completed', team: 'active', resource_progress: resourceProgressSnapshot };
|
||||
return;
|
||||
}
|
||||
safetyProgress.value = { company: 'completed', department: 'completed', team: 'completed', resource_progress: resourceProgressSnapshot };
|
||||
};
|
||||
|
||||
/**
|
||||
* 进入安全培训考试阶段并初始化本轮考试状态。
|
||||
* AI 触发时机:当三级学习全部完成,或员工在安全培训中点击“开始考试/重新考试”时调用。
|
||||
*/
|
||||
const enterSafetyExam = () => {
|
||||
if (totalQuestionCount.value <= 0) {
|
||||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||||
return;
|
||||
}
|
||||
safetyStage.value = 'exam';
|
||||
safetyViewStage.value = 'exam';
|
||||
stage.value = 'exam';
|
||||
attemptCount.value += 1;
|
||||
resetExamState();
|
||||
};
|
||||
|
||||
/**
|
||||
* 把后端培训记录回填到当前工作区状态。
|
||||
* AI 触发时机:页面刷新、重新进入聊天页或切换培训类型后,需要把服务端快照完整恢复到本地状态机。
|
||||
*/
|
||||
const applyProgressRecord = (record: TrainingProgressRecord | null) => {
|
||||
if (!record) {
|
||||
trainingVersion.value = DEFAULT_TRAINING_VERSION[learnerTab.value];
|
||||
examMode.value = 'unified';
|
||||
resetSafetyProgress('company');
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
currentJoinDate.value = null;
|
||||
latestSettledResult.value = null;
|
||||
return;
|
||||
}
|
||||
trainingVersion.value = record.trainingVersion || DEFAULT_TRAINING_VERSION[learnerTab.value];
|
||||
examMode.value = record.examMode || 'unified';
|
||||
if (learnerTab.value === 'safety') {
|
||||
safetyStage.value = record.safetyStage || 'company';
|
||||
safetyProgress.value = record.safetyProgress;
|
||||
safetyViewStage.value = record.safetyStage || 'company';
|
||||
}
|
||||
stage.value = record.stage;
|
||||
syncExamQuestionIndex(record.currentQuestionIndex);
|
||||
score.value = Number(record.score || 0);
|
||||
@@ -387,8 +548,19 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
syncAnswerStateForCurrentQuestion();
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装当前培训工作区的持久化载荷。
|
||||
* AI 触发时机:每次阶段推进、答题、结算或安全培训切级后,都要把统一格式的快照发送给后端保存。
|
||||
*/
|
||||
const buildProgressPayload = () => ({
|
||||
stage: stage.value,
|
||||
agentId: currentTrainingAgentId.value,
|
||||
stage: learnerTab.value === 'safety'
|
||||
? (safetyStage.value === 'exam' ? 'exam' : safetyStage.value === 'result' ? 'result' : 'summary')
|
||||
: stage.value,
|
||||
trainingVersion: trainingVersion.value,
|
||||
examMode: examMode.value,
|
||||
safetyStage: learnerTab.value === 'safety' ? safetyStage.value : null,
|
||||
safetyProgress: learnerTab.value === 'safety' ? safetyProgress.value : null,
|
||||
currentQuestionIndex: currentQuestionIndex.value,
|
||||
score: score.value,
|
||||
passed: isPassed.value,
|
||||
@@ -401,7 +573,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
if (!isTrainingAgent.value) return;
|
||||
persistQueue = persistQueue.catch(() => undefined).then(async () => {
|
||||
try {
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload());
|
||||
const saved = await saveMyTrainingProgress(buildProgressPayload(), learnerTab.value);
|
||||
hasWarnedPersistFailure.value = false;
|
||||
currentJoinDate.value = saved.joinDate || currentJoinDate.value;
|
||||
completionDate.value = saved.completionDate;
|
||||
@@ -433,7 +605,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const record = await getMyTrainingProgress();
|
||||
const record = await getMyTrainingProgress(learnerTab.value);
|
||||
hasWarnedLoadFailure.value = false;
|
||||
applyProgressRecord(record);
|
||||
} catch (error) {
|
||||
@@ -459,6 +631,24 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
}
|
||||
};
|
||||
|
||||
const loadTrainingConfig = async () => {
|
||||
if (!isTrainingAgent.value || !hasAuthenticatedUser.value) {
|
||||
publishedConfig.value = null;
|
||||
trainingConfigLoading.value = false;
|
||||
return;
|
||||
}
|
||||
trainingConfigLoading.value = true;
|
||||
try {
|
||||
publishedConfig.value = await getMyTrainingConfig(learnerTab.value);
|
||||
} catch (error) {
|
||||
if (!(error instanceof BusinessError && error.status === 401)) {
|
||||
publishedConfig.value = null;
|
||||
}
|
||||
} finally {
|
||||
trainingConfigLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadAdminRecords = async () => {
|
||||
if (!isTrainingAgent.value || !isAdminViewer.value) return;
|
||||
try {
|
||||
@@ -466,6 +656,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
keyword: hrKeyword.value || undefined,
|
||||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||||
status: hrStatusFilter.value,
|
||||
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
|
||||
};
|
||||
const [recordData, statsData] = await Promise.all([
|
||||
listTrainingRecords(query),
|
||||
@@ -494,6 +685,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
hasAuthenticatedUser,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
learnerTab,
|
||||
],
|
||||
([agent, loggedIn]) => {
|
||||
if (!matchesTrainingAgent(agent)) {
|
||||
@@ -516,6 +708,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
return;
|
||||
}
|
||||
isHydrated.value = false;
|
||||
void loadTrainingConfig();
|
||||
void loadTrainingProgress();
|
||||
},
|
||||
{ immediate: true },
|
||||
@@ -528,6 +721,7 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
hrKeyword,
|
||||
hrStatusFilter,
|
||||
hrDepartmentFilter,
|
||||
hrTypeFilter,
|
||||
() => String(currentUser.value?.username || '').trim(),
|
||||
() => String(currentUser.value?.role || '').trim(),
|
||||
],
|
||||
@@ -539,11 +733,30 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
);
|
||||
|
||||
const markVideoCompleted = () => {
|
||||
if (!hasPublishedTrainingConfig.value || !videoUrl.value) return;
|
||||
if (learnerTab.value === 'safety') {
|
||||
if (safetyStage.value === 'company') {
|
||||
resetSafetyProgress('department');
|
||||
} else if (safetyStage.value === 'department') {
|
||||
resetSafetyProgress('team');
|
||||
} else if (safetyStage.value === 'team') {
|
||||
resetSafetyProgress('exam');
|
||||
enterSafetyExam();
|
||||
}
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
stage.value = 'summary';
|
||||
void persistProgress();
|
||||
};
|
||||
|
||||
const startExam = () => {
|
||||
if (!hasPublishedTrainingConfig.value) return;
|
||||
if (learnerTab.value === 'safety') {
|
||||
enterSafetyExam();
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
if (totalQuestionCount.value <= 0) {
|
||||
msg.warning(t('chat.training.errors.questionBankEmpty'));
|
||||
return;
|
||||
@@ -614,6 +827,10 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
const submitExam = () => {
|
||||
if (!examReadyToSubmit.value) return;
|
||||
stage.value = 'result';
|
||||
if (learnerTab.value === 'safety') {
|
||||
safetyStage.value = 'result';
|
||||
safetyViewStage.value = 'result';
|
||||
}
|
||||
completionDate.value = formatDate(new Date());
|
||||
latestSettledResult.value = {
|
||||
score: score.value,
|
||||
@@ -625,16 +842,34 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
};
|
||||
|
||||
const restartExam = () => {
|
||||
if (learnerTab.value === 'safety') {
|
||||
enterSafetyExam();
|
||||
void persistProgress();
|
||||
return;
|
||||
}
|
||||
stage.value = 'video';
|
||||
resetExamState();
|
||||
// 不立即覆盖后端已结算成绩,避免刷新页面或重新进入历史对话时丢失上一轮考试结果与 HR 统计事实。
|
||||
};
|
||||
|
||||
/**
|
||||
* 按右侧步骤面板切换安全培训阶段。
|
||||
* AI 触发时机:当员工点击安全培训流程步骤时,只允许查看当前可达阶段,
|
||||
* 但绝不能因为“返回查看已完成阶段”而重置已保存的完成状态或学习记录。
|
||||
*/
|
||||
const setSafetyStage = (nextStage: SafetyStage) => {
|
||||
if (!hasPublishedTrainingConfig.value) return;
|
||||
const target = safetyStepItems.value.find((item) => item.id === nextStage);
|
||||
if (!target || target.status === 'locked') return;
|
||||
safetyViewStage.value = nextStage;
|
||||
};
|
||||
|
||||
const exportRecords = async () => {
|
||||
await exportTrainingRecords({
|
||||
keyword: hrKeyword.value || undefined,
|
||||
department: hrDepartmentFilter.value === 'all' ? undefined : hrDepartmentFilter.value,
|
||||
status: hrStatusFilter.value,
|
||||
type: hrTypeFilter.value === 'all' ? undefined : hrTypeFilter.value,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -642,6 +877,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.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}%`,
|
||||
@@ -691,17 +927,109 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
});
|
||||
|
||||
const showVideoModal = ref(false);
|
||||
const currentViewingMaterialId = ref<number | null>(null);
|
||||
const materialStartTime = ref<number>(0);
|
||||
|
||||
const startMaterialTimer = (materialId: number) => {
|
||||
currentViewingMaterialId.value = materialId;
|
||||
materialStartTime.value = Date.now();
|
||||
};
|
||||
|
||||
const stopMaterialTimer = () => {
|
||||
if (!currentViewingMaterialId.value || !materialStartTime.value) return;
|
||||
const materialId = String(currentViewingMaterialId.value);
|
||||
// 累计观看时长(秒)
|
||||
const durationSeconds = Math.round((Date.now() - materialStartTime.value) / 1000);
|
||||
const resource = (publishedConfig.value?.resources || []).find((item) => String(item.id) === materialId);
|
||||
|
||||
if (resource) {
|
||||
if (!safetyProgress.value.resource_progress) {
|
||||
safetyProgress.value.resource_progress = {};
|
||||
}
|
||||
const existing = safetyProgress.value.resource_progress[materialId] || { duration: 0, completed: false };
|
||||
existing.duration += durationSeconds;
|
||||
|
||||
const reqDurationMinutes = resource.requiredDuration || 0;
|
||||
if (existing.duration >= reqDurationMinutes * 60) {
|
||||
existing.completed = true;
|
||||
}
|
||||
safetyProgress.value.resource_progress[materialId] = existing;
|
||||
|
||||
checkAndAdvanceStage();
|
||||
}
|
||||
|
||||
currentViewingMaterialId.value = null;
|
||||
materialStartTime.value = 0;
|
||||
};
|
||||
|
||||
const checkAndAdvanceStage = () => {
|
||||
const activeStageMaterials = learnerTab.value === 'safety'
|
||||
? resolveSafetyStageMaterials(activeSafetyLearningStage.value)
|
||||
: publishedTrainingMaterials.value;
|
||||
if (!activeStageMaterials.length) return;
|
||||
const allCompleted = activeStageMaterials.every(m => {
|
||||
if (m.id == null) return true;
|
||||
const progress = safetyProgress.value.resource_progress?.[String(m.id)];
|
||||
return progress?.completed;
|
||||
});
|
||||
|
||||
if (allCompleted) {
|
||||
if (learnerTab.value === 'safety') {
|
||||
if (safetyStage.value === 'company') {
|
||||
resetSafetyProgress('department');
|
||||
} else if (safetyStage.value === 'department') {
|
||||
resetSafetyProgress('team');
|
||||
} else if (safetyStage.value === 'team') {
|
||||
resetSafetyProgress('exam');
|
||||
enterSafetyExam();
|
||||
}
|
||||
} else {
|
||||
stage.value = 'summary';
|
||||
}
|
||||
void persistProgress();
|
||||
} else {
|
||||
void persistProgress();
|
||||
}
|
||||
};
|
||||
|
||||
const videoUrl = computed(() => {
|
||||
const uploadedGuide = resolveTrainingVideoGuide(currentGuides.value);
|
||||
if (!publishedConfig.value) return '';
|
||||
const visibleGuideStage = visibleSafetyLearningStage.value || activeSafetyLearningStage.value;
|
||||
const preferredGuideIds = publishedTrainingMaterials.value
|
||||
.filter((resource) => resource.resourceType === 'agent_guide' && resource.agentGuideId != null)
|
||||
.map((resource) => Number(resource.agentGuideId));
|
||||
const uploadedGuide = learnerTab.value === 'safety'
|
||||
? resolveSafetyTrainingVideoGuide(currentGuides.value, visibleGuideStage || 'company', preferredGuideIds)
|
||||
: currentGuides.value.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video');
|
||||
const uploadedGuideUrl = String(uploadedGuide?.file_url || uploadedGuide?.file_path || '').trim();
|
||||
return uploadedGuideUrl || resolveTrainingVideoUrl(currentAgent.value, DEFAULT_TRAINING_VIDEO_URL);
|
||||
const configuredGuide = publishedTrainingMaterials.value
|
||||
.find((resource) => resource.resourceType === 'agent_guide'
|
||||
&& resource.resource?.fileType === 'video'
|
||||
&& (learnerTab.value !== 'safety'
|
||||
|| !visibleGuideStage
|
||||
|| !SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|
||||
|| resource.resource.guideUsage === SAFETY_STAGE_GUIDE_USAGE_MAP[visibleGuideStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]));
|
||||
return String(configuredGuide?.resource?.fileUrl || '').trim()
|
||||
|| uploadedGuideUrl;
|
||||
});
|
||||
|
||||
return {
|
||||
isTrainingAgent,
|
||||
isAdminViewer,
|
||||
isHydrated,
|
||||
trainingConfigLoading,
|
||||
hasPublishedTrainingConfig,
|
||||
publishedTrainingMaterials,
|
||||
publishedSafetySummary,
|
||||
activeView,
|
||||
learnerTab,
|
||||
trainingVersion,
|
||||
examMode,
|
||||
safetyStage,
|
||||
safetyViewStage,
|
||||
safetyProgress,
|
||||
safetyProgressPercent,
|
||||
safetyStepItems,
|
||||
stage,
|
||||
currentQuestionIndex,
|
||||
currentQuestionNumber,
|
||||
@@ -731,8 +1059,9 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
currentUserEmployeeId,
|
||||
currentUserDepartment,
|
||||
hrKeyword,
|
||||
hrStatusFilter,
|
||||
hrDepartmentFilter,
|
||||
hrStatusFilter,
|
||||
hrTypeFilter,
|
||||
departmentOptions,
|
||||
filteredRecords,
|
||||
stats,
|
||||
@@ -748,8 +1077,13 @@ export function useTrainingWorkspace(options: UseTrainingWorkspaceOptions) {
|
||||
moveToNextQuestion,
|
||||
submitExam,
|
||||
restartExam,
|
||||
setSafetyStage,
|
||||
exportRecords,
|
||||
showVideoModal,
|
||||
videoUrl,
|
||||
startMaterialTimer,
|
||||
stopMaterialTimer,
|
||||
currentViewingMaterialId,
|
||||
currentTrainingAgentId,
|
||||
};
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
/**
|
||||
* features/chat/training/training.types.ts
|
||||
* 用途:定义入职培训聊天工作区的题库、考试进度、HR 统计记录等共享类型。
|
||||
* 依赖:被 useTrainingWorkspace 与 TrainingWorkspacePanel 共同引用。
|
||||
* 逻辑:统一约束“学员考试流”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
|
||||
* 用途:定义员工培训工作区的共享类型,覆盖入职培训、安全培训、考试过程和 HR 统计记录。
|
||||
* 依赖:被 useTrainingWorkspace、training.api 与 TrainingWorkspacePanel 共同引用。
|
||||
* 逻辑:统一约束“多培训类型学员流程”和“HR 管理流”的前端数据结构,避免组件内散落匿名对象。
|
||||
*/
|
||||
|
||||
export type TrainingType = 'onboarding' | 'safety';
|
||||
|
||||
export type TrainingStage = 'video' | 'summary' | 'exam' | 'result';
|
||||
|
||||
export type TrainingExamMode = 'unified' | 'per_level';
|
||||
|
||||
export type SafetyStage = 'company' | 'department' | 'team' | 'exam' | 'result';
|
||||
|
||||
export type TrainingWorkspaceView = 'learner' | 'admin';
|
||||
|
||||
export type TrainingQuestionType = 'single' | 'boolean';
|
||||
@@ -32,6 +38,33 @@ export interface TrainingContentConfig {
|
||||
questionBank: TrainingQuestion[];
|
||||
}
|
||||
|
||||
export interface TrainingPublishedConfigResource {
|
||||
id?: number | null;
|
||||
resourceType?: string | null;
|
||||
trainingLevel?: Exclude<SafetyStage, 'exam' | 'result'> | null;
|
||||
agentGuideId?: number | null;
|
||||
inlineQuestions?: unknown[];
|
||||
title?: string | null;
|
||||
sortOrder?: number;
|
||||
requiredDuration?: number;
|
||||
resource?: {
|
||||
id?: number;
|
||||
fileName?: string;
|
||||
fileType?: string;
|
||||
fileUrl?: string;
|
||||
guideUsage?: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface TrainingPublishedConfig {
|
||||
id: number;
|
||||
trainingType: TrainingType;
|
||||
version: string;
|
||||
passScore: number;
|
||||
settings: Record<string, unknown>;
|
||||
resources: TrainingPublishedConfigResource[];
|
||||
}
|
||||
|
||||
export interface TrainingAnswerRecord {
|
||||
questionId: string;
|
||||
selectedOptionId: string;
|
||||
@@ -50,8 +83,17 @@ export interface TrainingExamTransitionFeedback {
|
||||
|
||||
export type TrainingRecordStatus = 'passed' | 'failed' | 'in_progress';
|
||||
|
||||
export interface SafetyProgressState {
|
||||
company: string;
|
||||
department: string;
|
||||
team: string;
|
||||
resource_progress?: Record<string, { duration: number; completed: boolean }>;
|
||||
}
|
||||
|
||||
export interface TrainingRecord {
|
||||
id: string | number;
|
||||
trainingType?: TrainingType;
|
||||
trainingVersion?: string;
|
||||
name: string;
|
||||
employeeId: string;
|
||||
department: string;
|
||||
@@ -64,6 +106,9 @@ export interface TrainingRecord {
|
||||
|
||||
export interface TrainingProgressRecord extends TrainingRecord {
|
||||
stage: TrainingStage;
|
||||
examMode: TrainingExamMode;
|
||||
safetyStage: SafetyStage | null;
|
||||
safetyProgress: SafetyProgressState;
|
||||
currentQuestionIndex: number;
|
||||
passed: boolean;
|
||||
answerDetails: TrainingAnswerRecord[];
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 依赖:无运行时副作用,仅依赖 Agent extra_config 普通对象与 training.types。
|
||||
* 逻辑:统一判断某个 Agent 是否启用培训工作区,并解析培训视频、题库与复盘配置。
|
||||
*/
|
||||
import type { TrainingContentConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
|
||||
import type { TrainingContentConfig, TrainingPublishedConfig, TrainingQuestion, TrainingQuestionOption } from './training.types';
|
||||
|
||||
type TrainingAgentLike = {
|
||||
name?: string | null;
|
||||
@@ -24,6 +24,11 @@ export type TrainingGuideLike = {
|
||||
} | null | undefined;
|
||||
|
||||
export const TRAINING_CONTENT_PROFILE = 'training';
|
||||
export const SAFETY_STAGE_GUIDE_USAGE_MAP = {
|
||||
company: 'training_safety_company_video',
|
||||
department: 'training_safety_department_video',
|
||||
team: 'training_safety_team_video',
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 判断当前 Agent 是否应启用培训工作区。
|
||||
@@ -143,6 +148,30 @@ export function resolveTrainingVideoGuide(guides: TrainingGuideLike[] | null | u
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按安全培训当前级别查找对应视频指南。
|
||||
* AI 触发时机:当员工在安全培训中切换“公司级 / 部门级 / 班组级”阶段时,工作区必须优先展示该级别绑定的视频,而不是沿用通用安全培训视频。
|
||||
*/
|
||||
export function resolveSafetyTrainingVideoGuide(
|
||||
guides: TrainingGuideLike[] | null | undefined,
|
||||
safetyStage: keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP | 'exam' | 'result',
|
||||
preferredGuideIds: number[] = [],
|
||||
): TrainingGuideLike {
|
||||
const normalized = Array.isArray(guides) ? guides : [];
|
||||
const stageUsage = safetyStage in SAFETY_STAGE_GUIDE_USAGE_MAP
|
||||
? SAFETY_STAGE_GUIDE_USAGE_MAP[safetyStage as keyof typeof SAFETY_STAGE_GUIDE_USAGE_MAP]
|
||||
: null;
|
||||
return (
|
||||
normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video' && (!stageUsage || guide?.guide_usage === stageUsage))
|
||||
|| normalized.find((guide) => guide?.id != null && preferredGuideIds.includes(Number(guide.id)) && guide?.file_type === 'video')
|
||||
|| (stageUsage
|
||||
? normalized.find((guide) => guide?.guide_usage === stageUsage && guide?.file_type === 'video')
|
||||
: null)
|
||||
|| normalized.find((guide) => guide?.guide_usage === 'training_safety_video' && guide?.file_type === 'video')
|
||||
|| null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找培训工作区优先使用的试题 PDF。
|
||||
* AI 触发时机:当员工培训页需要为学员提供“查看试题 PDF”入口时使用,避免把普通指南 PDF 错当成考试资料。
|
||||
@@ -163,24 +192,35 @@ export function resolveTrainingContentConfig(
|
||||
agent: TrainingAgentLike,
|
||||
fallback: TrainingContentConfig,
|
||||
booleanOptions: TrainingQuestionOption[],
|
||||
publishedConfig?: TrainingPublishedConfig | null,
|
||||
): TrainingContentConfig {
|
||||
if (!publishedConfig) {
|
||||
return { passScore: fallback.passScore, summaryPoints: [], summaryChecklist: [], questionBank: [] };
|
||||
}
|
||||
const extraConfig = asRecord(agent?.extra_config);
|
||||
const trainingConfig = asRecord(extraConfig.training_config);
|
||||
const mergedConfig = {
|
||||
...extraConfig,
|
||||
...trainingConfig,
|
||||
...(publishedConfig.settings || {}),
|
||||
};
|
||||
|
||||
const publishedQuestions = (publishedConfig?.resources || [])
|
||||
.filter((resource) => resource.resourceType === 'inline_questions')
|
||||
.flatMap((resource) => Array.isArray(resource.inlineQuestions) ? resource.inlineQuestions : []);
|
||||
|
||||
const summaryPoints = normalizeStringList(mergedConfig.summary_points ?? mergedConfig.summaryPoints);
|
||||
const summaryChecklist = normalizeStringList(mergedConfig.summary_checklist ?? mergedConfig.summaryChecklist);
|
||||
const questionBank = normalizeQuestionBank(
|
||||
mergedConfig.question_bank ?? mergedConfig.questionBank,
|
||||
publishedQuestions.length
|
||||
? publishedQuestions
|
||||
: mergedConfig.questions ?? mergedConfig.question_bank ?? mergedConfig.questionBank,
|
||||
booleanOptions,
|
||||
);
|
||||
|
||||
return {
|
||||
passScore: normalizePassScore(
|
||||
mergedConfig.pass_score ?? mergedConfig.passScore,
|
||||
publishedConfig?.passScore ?? mergedConfig.pass_score ?? mergedConfig.passScore,
|
||||
fallback.passScore || DEFAULT_PASS_SCORE,
|
||||
),
|
||||
summaryPoints: summaryPoints.length ? summaryPoints : fallback.summaryPoints,
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
"shippingLegacyStpJobs": "Legacy STP Jobs",
|
||||
"overview": "Overview",
|
||||
"linkedServices": "Linked Services",
|
||||
"procurementContract": "Procurement Contract Review"
|
||||
"procurementContract": "Procurement Contract Review",
|
||||
"trainingConfig": "Training Config"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "READ-ONLY RUN DIAGNOSTICS",
|
||||
@@ -1098,12 +1099,7 @@
|
||||
"deleteFailed": "Failed to delete shipping inventory configuration"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "Guide Usage",
|
||||
"generalGuide": "General Guide",
|
||||
"trainingVideo": "Employee Training Video",
|
||||
"trainingExamPdf": "Employee Training Exam PDF",
|
||||
"guideUsageHint": "The training workspace will prioritize guides marked as employee training video or employee training exam PDF.",
|
||||
"subtitle": "Manage onboarding guides for apps (video, PDF, and more)",
|
||||
"subtitle": "Manage onboarding guides for apps (video, PDF, and more)",
|
||||
"selectAgent": "Select app:",
|
||||
"addGuide": "Add Guide",
|
||||
"editGuide": "Edit Guide",
|
||||
@@ -4859,4 +4855,7 @@
|
||||
"regionSaved": "Comparison region configuration saved",
|
||||
"defaultTemplateName": "Standard Procurement Contract"
|
||||
}
|
||||
,"trainingConfig": {
|
||||
"title": "Training Configuration", "subtitle": "Manage versions, exam rules, resources and questions by training type", "types": "Training Types", "typeCount": "{count} configurations", "detail": "Configuration Details", "headerMeta": "Type: {type} · Current version: {version}", "addType": "Add Training Type", "editType": "Edit Training Type", "empty": "No training configurations", "selectHint": "Select a training type", "saving": "Saving...", "addResource": "Add Resource", "selectResource": "Select a resource", "resourceTitle": "Resource name", "resourceTitlePlaceholder": "Enter a learner-facing resource name", "resourceKind": "Resource type", "resourceFile": "Linked content", "resourcesEmpty": "No training materials added", "resourcesEmptyHint": "Link an application guide video or knowledge document version", "guideGroupingHint": "Safety training guides are grouped by usage for accurate company, department, or team-level linking", "documentVersionHint": "The configuration locks the selected knowledge document version", "questionJson": "Question JSON", "questionSource": "Training exam PDF", "selectQuestionSource": "Select the current PDF from Employee Training", "parseQuestions": "Convert to question bank", "parsingQuestions": "Parsing...", "questionSourceHint": "Only current PDF versions from the Employee Training knowledge base are listed. You can edit the JSON after parsing.", "parseStatus": "Parsed {fileName} ({mode})", "parseSkipped": "; unrecognized question numbers: {numbers}", "questionJsonHint": "Enter a JSON array. Saving syncs it to settings and the inline question resource.", "questionCount": "{count} questions", "confirmDelete": "Delete this training configuration?", "sections": {"basicTitle": "Basic Configuration", "basicDesc": "Set the training name, release version, status, and exam rules", "resourcesTitle": "Training Materials", "resourcesDesc": "Link guide videos and knowledge documents to build learning content", "examTitle": "Question Bank", "examDesc": "Maintain structured question data for controlled examinations", "reviewTitle": "Review & Checklist", "reviewDesc": "Configure review points, pre-exam checklists, and guided chat questions"}, "guideGroups": {"company": "Company-level Safety Training", "department": "Department-level Safety Training", "team": "Team-level Safety Training", "other": "General and Other Materials"}, "placeholders": {"onePerLine": "Enter one item per line", "oneQuestionPerLine": "Enter one question per line"}, "fields": {"type": "Training type code", "name": "Configuration name", "version": "Version", "status": "Status", "passScore": "Pass score", "examMode": "Exam mode", "summaryPoints": "Review points", "summaryChecklist": "Pre-exam checklist", "employeeQuestions": "Employee FAQs", "hrQuestions": "HR FAQs"}, "status": {"draft": "Draft", "published": "Published", "archived": "Archived"}, "examMode": {"unified": "Unified paper", "perLevel": "Per-level exam"}, "resourceTypes": {"questions": "Inline questions", "guide": "Guide resource", "document": "Knowledge document"}, "messages": {"loadFailed": "Failed to load training configurations", "saveFailed": "Failed to save training configuration", "typeRequired": "Enter the training type code and name", "invalidQuestions": "Question JSON must be an array", "questionSourceRequired": "Select a training exam PDF", "parseSuccess": "Parsed {count} questions. Review before saving.", "parseFailed": "Question bank parsing failed", "saved": "Training configuration saved", "deleted": "Training configuration deleted"}
|
||||
}
|
||||
}
|
||||
@@ -1047,6 +1047,7 @@
|
||||
"progressPercent": "Completion",
|
||||
"stepNo": "Step {value}",
|
||||
"defaultLearnerName": "Current learner",
|
||||
"noContent": { "loading": "Loading training content...", "title": "No training content", "description": "The administrator has not published the current training configuration yet." },
|
||||
"unknownDepartment": "Department pending",
|
||||
"video": {
|
||||
"title": "Step 1: Watch the training video",
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
"overview": "ภาพรวม",
|
||||
"linkedServices": "บริการที่เชื่อมโยง",
|
||||
"platformApps": "แอปแพลตฟอร์ม",
|
||||
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ"
|
||||
"procurementContract": "ตรวจสอบสัญญาจัดซื้อ",
|
||||
"trainingConfig": "การกำหนดค่าการฝึกอบรม"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "การวินิจฉัยการทำงานแบบอ่านอย่างเดียว",
|
||||
@@ -1098,12 +1099,7 @@
|
||||
"deleteFailed": "ลบการตั้งค่าสินค้าคงคลังขนส่งไม่สำเร็จ"
|
||||
},
|
||||
"platformApps": {
|
||||
"guideUsage": "ประเภทการใช้งานเอกสาร",
|
||||
"generalGuide": "คู่มือทั่วไป",
|
||||
"trainingVideo": "วิดีโออบรมพนักงาน",
|
||||
"trainingExamPdf": "PDF ข้อสอบอบรมพนักงาน",
|
||||
"guideUsageHint": "พื้นที่อบรมจะให้ความสำคัญกับเอกสารที่ทำเครื่องหมายเป็นวิดีโออบรมพนักงานหรือ PDF ข้อสอบอบรมพนักงานก่อน",
|
||||
"subtitle": "จัดการเอกสารคู่มือเริ่มต้นของแอป (รองรับวิดีโอ PDF ฯลฯ)",
|
||||
"subtitle": "จัดการเอกสารคู่มือเริ่มต้นของแอป (รองรับวิดีโอ PDF ฯลฯ)",
|
||||
"selectAgent": "เลือกแอป:",
|
||||
"addGuide": "เพิ่มคู่มือ",
|
||||
"editGuide": "แก้ไขคู่มือ",
|
||||
@@ -4728,4 +4724,7 @@
|
||||
"regionSaved": "บันทึกการตั้งค่าพื้นที่เปรียบเทียบแล้ว",
|
||||
"defaultTemplateName": "สัญญาจัดซื้อมาตรฐาน"
|
||||
}
|
||||
,"trainingConfig": {
|
||||
"title": "การกำหนดค่าการฝึกอบรม", "subtitle": "จัดการเวอร์ชัน กฎการสอบ ทรัพยากร และคำถามตามประเภทการฝึกอบรม", "types": "ประเภทการฝึกอบรม", "typeCount": "ทั้งหมด {count} การกำหนดค่า", "detail": "รายละเอียดการกำหนดค่า", "headerMeta": "ประเภท: {type} · เวอร์ชันปัจจุบัน: {version}", "addType": "เพิ่มประเภทการฝึกอบรม", "editType": "แก้ไขประเภทการฝึกอบรม", "empty": "ยังไม่มีการกำหนดค่า", "selectHint": "เลือกประเภทการฝึกอบรม", "saving": "กำลังบันทึก...", "addResource": "เพิ่มทรัพยากร", "selectResource": "เลือกทรัพยากร", "resourceTitle": "ชื่อทรัพยากร", "resourceTitlePlaceholder": "กรอกชื่อทรัพยากรสำหรับผู้เรียน", "resourceKind": "ประเภททรัพยากร", "resourceFile": "เนื้อหาที่เชื่อมโยง", "resourcesEmpty": "ยังไม่ได้เพิ่มเอกสารฝึกอบรม", "resourcesEmptyHint": "เชื่อมโยงวิดีโอคู่มือแอปหรือเวอร์ชันเอกสารคลังความรู้", "guideGroupingHint": "คู่มือความปลอดภัยจัดกลุ่มตามการใช้งาน เพื่อเชื่อมโยงระดับบริษัท แผนก หรือทีมได้ถูกต้อง", "documentVersionHint": "การกำหนดค่าจะล็อกเวอร์ชันเอกสารคลังความรู้ที่เลือก", "questionJson": "JSON คำถาม", "questionSource": "PDF ข้อสอบฝึกอบรม", "selectQuestionSource": "เลือก PDF ปัจจุบันจากคลังความรู้การฝึกอบรมพนักงาน", "parseQuestions": "แปลงเป็นคลังข้อสอบ", "parsingQuestions": "กำลังวิเคราะห์...", "questionSourceHint": "แสดงเฉพาะ PDF เวอร์ชันปัจจุบันจากคลังความรู้การฝึกอบรมพนักงาน หลังวิเคราะห์แล้วยังแก้ไข JSON ได้", "parseStatus": "วิเคราะห์ {fileName} แล้ว ({mode})", "parseSkipped": "; หมายเลขข้อที่ไม่รู้จัก: {numbers}", "questionJsonHint": "ป้อนอาร์เรย์ JSON เมื่อบันทึกระบบจะซิงค์ไปยัง settings และทรัพยากรคำถามในตัว", "questionCount": "{count} ข้อ", "confirmDelete": "ลบการกำหนดค่านี้หรือไม่", "sections": {"basicTitle": "การกำหนดค่าพื้นฐาน", "basicDesc": "ตั้งชื่อการฝึกอบรม เวอร์ชันเผยแพร่ สถานะ และกฎการสอบ", "resourcesTitle": "เอกสารฝึกอบรม", "resourcesDesc": "เชื่อมโยงวิดีโอคู่มือและเอกสารความรู้เพื่อสร้างเนื้อหาการเรียน", "examTitle": "คลังข้อสอบ", "examDesc": "ดูแลข้อมูลคำถามแบบมีโครงสร้างสำหรับการสอบที่ควบคุม", "reviewTitle": "ทบทวนและรายการตรวจสอบ", "reviewDesc": "กำหนดประเด็นทบทวน รายการก่อนสอบ และคำถามแนะนำในการสนทนา"}, "guideGroups": {"company": "การฝึกอบรมความปลอดภัยระดับบริษัท", "department": "การฝึกอบรมความปลอดภัยระดับแผนก", "team": "การฝึกอบรมความปลอดภัยระดับทีม", "other": "เอกสารทั่วไปและอื่น ๆ"}, "placeholders": {"onePerLine": "กรอกหนึ่งรายการต่อบรรทัด", "oneQuestionPerLine": "กรอกหนึ่งคำถามต่อบรรทัด"}, "fields": {"type": "รหัLine truncated
|
||||
}
|
||||
}
|
||||
@@ -1047,6 +1047,7 @@
|
||||
"progressPercent": "เปอร์เซ็นต์เสร็จสิ้น",
|
||||
"stepNo": "ขั้นตอน {value}",
|
||||
"defaultLearnerName": "ผู้เรียนปัจจุบัน",
|
||||
"noContent": { "loading": "กำลังโหลดเนื้อหาการฝึกอบรม...", "title": "ยังไม่มีเนื้อหาการฝึกอบรม", "description": "ผู้ดูแลระบบยังไม่ได้เผยแพร่การกำหนดค่าการฝึกอบรมปัจจุบัน" },
|
||||
"unknownDepartment": "ยังไม่ได้ระบุแผนก",
|
||||
"video": {
|
||||
"title": "ขั้นตอน 1: ดูวิดีโออบรม",
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
"shippingLegacyStpJobs": "历史 STP Job",
|
||||
"overview": "概览",
|
||||
"linkedServices": "关联服务",
|
||||
"procurementContract": "采购合同审查"
|
||||
"procurementContract": "采购合同审查",
|
||||
"trainingConfig": "培训配置"
|
||||
},
|
||||
"shippingFieldAssets": {
|
||||
"title": "字段资产库",
|
||||
@@ -4838,4 +4839,51 @@
|
||||
"regionSaved": "比对区域配置已保存",
|
||||
"defaultTemplateName": "标准采购合同"
|
||||
}
|
||||
,"trainingConfig": {
|
||||
"eyebrow": "培训运营中心",
|
||||
"title": "培训配置",
|
||||
"subtitle": "按培训类型管理版本、考试规则、资源与题目",
|
||||
"pageHint": "配置变更将在保存后生效",
|
||||
"footerHint": "所有配置项均支持保存后继续调整",
|
||||
"stats": {"total": "配置总数", "published": "已发布", "resources": "当前资料", "levels": "已配置级别"},
|
||||
"types": "培训类型",
|
||||
"typeCount": "共 {count} 个配置",
|
||||
"detail": "配置详情",
|
||||
"headerMeta": "类型编码:{type} · 当前版本:{version}",
|
||||
"addType": "新增培训类型",
|
||||
"editType": "编辑培训类型",
|
||||
"empty": "暂无培训配置",
|
||||
"selectHint": "请选择培训类型",
|
||||
"saving": "保存中...",
|
||||
"addResource": "添加资源",
|
||||
"selectResource": "请选择资源",
|
||||
"resourceTitle": "资源名称",
|
||||
"resourceTitlePlaceholder": "填写面向学员的资源名称",
|
||||
"resourceKind": "资源类型",
|
||||
"resourceFile": "关联资料",
|
||||
"resourcesEmpty": "尚未添加培训资料",
|
||||
"resourcesEmptyHint": "可关联应用指南视频或知识库文档版本",
|
||||
"guideGroupingHint": "安全培训指南按用途分组,便于准确关联公司级、部门级或班组级资料",
|
||||
"documentVersionHint": "配置将锁定所选知识库文档版本",
|
||||
"questionJson": "题目 JSON",
|
||||
"questionSource": "培训试题 PDF",
|
||||
"selectQuestionSource": "请选择员工培训知识库当前 PDF",
|
||||
"parseQuestions": "转为题库",
|
||||
"parsingQuestions": "解析中...",
|
||||
"questionSourceHint": "仅显示“员工培训”知识库的当前 PDF 版本;解析后仍可手工修改 JSON。",
|
||||
"parseStatus": "已解析《{fileName}》({mode})",
|
||||
"parseSkipped": ",未识别题号:{numbers}",
|
||||
"questionJsonHint": "请输入 JSON 数组;保存时将同步到配置 settings 与内嵌题目资源。",
|
||||
"questionCount": "{count} 道题",
|
||||
"questionBankTitle": "入职培训题库",
|
||||
"confirmDelete": "确定删除该培训配置吗?",
|
||||
"sections": {"basicTitle": "基础配置", "basicDesc": "设置培训名称、发布版本、状态及考试规则", "resourcesTitle": "培训资料", "resourcesDesc": "关联视频指南与知识库文档,构建学员学习内容", "examTitle": "考试题库", "examDesc": "维护受控考试使用的结构化题目数据", "reviewTitle": "复盘与清单", "reviewDesc": "配置培训完成后的复盘重点、考前清单与聊天引导问题"},
|
||||
"guideGroups": {"company": "公司级安全培训", "department": "部门级安全培训", "team": "班组级安全培训", "other": "通用及其他资料"},
|
||||
"placeholders": {"onePerLine": "每行填写一项", "oneQuestionPerLine": "每行填写一个问题"},
|
||||
"fields": {"type": "培训类型编码", "name": "配置名称", "version": "版本", "status": "状态", "passScore": "及格分数", "examMode": "考试模式", "summaryPoints": "复盘要点", "summaryChecklist": "考前清单", "employeeQuestions": "员工常见问题", "hrQuestions": "HR 常见问题"},
|
||||
"status": {"draft": "草稿", "published": "已发布", "archived": "已归档"},
|
||||
"examMode": {"unified": "统一试卷", "perLevel": "按级别考试"},
|
||||
"resourceTypes": {"questions": "内置题目", "guide": "指南资源", "document": "知识库文档"},
|
||||
"messages": {"loadFailed": "加载培训配置失败", "saveFailed": "保存培训配置失败", "typeRequired": "请填写培训类型编码和名称", "invalidQuestions": "题目 JSON 格式无效,必须是数组", "questionSourceRequired": "请选择培训试题 PDF", "parseSuccess": "已解析 {count} 道题目,请复核后保存", "parseFailed": "题库解析失败", "saved": "培训配置已保存", "deleted": "培训配置已删除"}
|
||||
}
|
||||
}
|
||||
@@ -1081,6 +1081,7 @@
|
||||
"progressPercent": "完成度",
|
||||
"stepNo": "步骤 {value}",
|
||||
"defaultLearnerName": "当前学员",
|
||||
"noContent": { "loading": "正在加载培训内容...", "title": "暂无培训内容", "description": "管理员尚未发布当前培训配置,请稍后再试。" },
|
||||
"unknownDepartment": "待补充部门",
|
||||
"video": {
|
||||
"title": "第一步:观看培训视频",
|
||||
@@ -1141,6 +1142,75 @@
|
||||
"rule3": "低于 {passScore} 分判定为未通过,必须重新考试。",
|
||||
"rule4": "HR 管理端可在同一聊天页查看统计并导出 Excel。"
|
||||
},
|
||||
"safety": {
|
||||
"tabs": {
|
||||
"onboarding": "入职培训",
|
||||
"safety": "安全培训"
|
||||
},
|
||||
"progressTitle": "三级安全教育培训进度",
|
||||
"progressHint": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料/视频后,进入1次统一考试,≥90分及格方可结业。",
|
||||
"steps": {
|
||||
"company": "01 · 公司级",
|
||||
"department": "02 · 部门级",
|
||||
"team": "03 · 班组级",
|
||||
"exam": "04 · 统一考试"
|
||||
},
|
||||
"stepStatus": {
|
||||
"watchVideo": "观看视频",
|
||||
"examReq": "≥90 分及格",
|
||||
"completed": "已完成",
|
||||
"inProgress": "进行中",
|
||||
"pending": "待学习",
|
||||
"examPending": "需先学完三级"
|
||||
},
|
||||
"videoPanelTitle": "{level} 第{step}步",
|
||||
"videoPanelSubtitle": "观看安全教育培训视频",
|
||||
"videoPanelPassLine": "及格线:≥ 90分方可进入考试",
|
||||
"videoTitle": "部门安全生产管理制度宣导",
|
||||
"videoDuration": "时长 35 分钟 · 已完成 12%",
|
||||
"materialsTitle": "培训资料清单 (共 3 个文件/视频)",
|
||||
"materials": {
|
||||
"m1": "部门安全生产管理制度宣导.mp4",
|
||||
"m2": "危险化学品安全操作规程.pdf",
|
||||
"m3": "消防应急疏散演练视频.mp4"
|
||||
},
|
||||
"flowTitle": "学习与考试流程",
|
||||
"flowSteps": {
|
||||
"company": "公司级安全教育",
|
||||
"department": "部门级安全教育",
|
||||
"team": "班组级安全教育",
|
||||
"exam": "统一考试 ≥90分"
|
||||
},
|
||||
"summaryTitle": "培训总结",
|
||||
"summaryContent": {
|
||||
"company": [
|
||||
"1公司教育:国家有关安全生产方针、政策、法律、法规和有关规定。",
|
||||
"2公司安全生产特点、有关安全管理标准和制度、安全生产情况及安全生产基本知识。",
|
||||
"3企业安全生产规章制度、安全纪律和劳动纪律。",
|
||||
"4安全生产和职业卫生的基本知识(防机械伤害、安全用电、防火防爆、防尘防毒、急救、危险因素、应急预案等)。",
|
||||
"5作业场所和工作岗位存在的危险因素、防范措施及事故应急措施;",
|
||||
"6安全生产正反方面的经验和教训,及重大事故安全案例教训。",
|
||||
"7从业人员安全生产权利和义务;"
|
||||
],
|
||||
"department": [
|
||||
"1部门概况、生产或作业特点、可能存在的不安全因素及必须遵守的事项。",
|
||||
"2公司、部门安全生产状况、管理制度规定和安全注意事项。",
|
||||
"3所从事工种的安全技术操作规程、安全职责、操作技能及强制性标准。",
|
||||
"4一般的机械设备、电气、触电、中暑、中毒急救安全基础知识",
|
||||
"5作业场所和工作岗位存在的风险、部门危险因素分布、安全通道、职业危害、伤亡事故、应急救缓预案内容。防火、防毒、防尘、防爆知识及紧急情况安全处置、自救互救、急救方法、疏散和现场紧急情况的处理。",
|
||||
"6部门安全设施(工具)、安全警示标志、急救器材、消防器材和个人防护用品的性能、使用方法和维护。",
|
||||
"7部门以往发生的典型安全和职业危害事故教育、岗位预防措施等。",
|
||||
"8有关事故案例。"
|
||||
],
|
||||
"team": [
|
||||
"1本班组(岗位)生产工艺流程、作业特点和注意事项、安全操作规程及细则。",
|
||||
"2本班组安全活动制度及纪律、岗位之间工作衔接配合的安全与职业卫生事项。",
|
||||
"3本班组(岗位)设备、工具的性能和安全装置、安全设施、监控仪器的作用原理、正确使用方法、防护用品及消防器材的使用和保管方法等。",
|
||||
"4危害因素及防范、应急措施,本岗位易发生事故的不安全因素及其防范对策,本工种事故案例剖析。",
|
||||
"5本岗位发现紧急情况应采取的应救措施和报告办法。"
|
||||
]
|
||||
}
|
||||
},
|
||||
"hr": {
|
||||
"stats": {
|
||||
"total": "参训人数",
|
||||
@@ -1154,8 +1224,12 @@
|
||||
"keywordPlaceholder": "输入姓名或工号筛选",
|
||||
"statusLabel": "状态",
|
||||
"departmentLabel": "部门",
|
||||
"typeLabel": "培训类型",
|
||||
"allStatuses": "全部状态",
|
||||
"allDepartments": "全部部门",
|
||||
"allTypes": "全部培训",
|
||||
"typeOnboarding": "入职培训",
|
||||
"typeSafety": "安全培训",
|
||||
"noLimit": "不限"
|
||||
},
|
||||
"columns": {
|
||||
|
||||
@@ -45,7 +45,8 @@
|
||||
"overview": "概覽",
|
||||
"linkedServices": "關聯服務",
|
||||
"platformApps": "平台應用說明",
|
||||
"procurementContract": "採購合同審查"
|
||||
"procurementContract": "採購合同審查",
|
||||
"trainingConfig": "培訓配置"
|
||||
},
|
||||
"shippingOrderExtractionRuns": {
|
||||
"eyebrow": "唯讀執行診斷",
|
||||
@@ -4728,4 +4729,7 @@
|
||||
"regionSaved": "比對區域設定已儲存",
|
||||
"defaultTemplateName": "標準採購合同"
|
||||
}
|
||||
,"trainingConfig": {
|
||||
"title": "培訓配置", "subtitle": "按培訓類型管理版本、考試規則、資源與題目", "types": "培訓類型", "typeCount": "共 {count} 個配置", "detail": "配置詳情", "headerMeta": "類型編碼:{type} · 目前版本:{version}", "addType": "新增培訓類型", "editType": "編輯培訓類型", "empty": "暫無培訓配置", "selectHint": "請選擇培訓類型", "saving": "儲存中...", "addResource": "新增資源", "selectResource": "請選擇資源", "resourceTitle": "資源名稱", "resourceTitlePlaceholder": "填寫面向學員的資源名稱", "resourceKind": "資源類型", "resourceFile": "關聯資料", "resourcesEmpty": "尚未新增培訓資料", "resourcesEmptyHint": "可關聯應用指南影片或知識庫文件版本", "guideGroupingHint": "安全培訓指南按用途分組,便於準確關聯公司級、部門級或班組級資料", "documentVersionHint": "配置將鎖定所選知識庫文件版本", "questionJson": "題目 JSON", "questionSource": "培訓試題 PDF", "selectQuestionSource": "請選擇員工培訓知識庫目前 PDF", "parseQuestions": "轉為題庫", "parsingQuestions": "解析中...", "questionSourceHint": "僅顯示員工培訓知識庫的目前 PDF 版本;解析後仍可手動修改 JSON。", "parseStatus": "已解析《{fileName}》({mode})", "parseSkipped": ",未識別題號:{numbers}", "questionJsonHint": "請輸入 JSON 陣列;儲存時將同步至配置 settings 與內嵌題目資源。", "questionCount": "{count} 道題", "confirmDelete": "確定刪除此培訓配置嗎?", "sections": {"basicTitle": "基礎配置", "basicDesc": "設定培訓名稱、發佈版本、狀態及考試規則", "resourcesTitle": "培訓資料", "resourcesDesc": "關聯影片指南與知識庫文件,建立學員學習內容", "examTitle": "考試題庫", "examDesc": "維護受控考試使用的結構化題目資料", "reviewTitle": "複盤與清單", "reviewDesc": "配置培訓完成後的複盤重點、考前清單與聊天引導問題"}, "guideGroups": {"company": "公司級安全培訓", "department": "部門級安全培訓", "team": "班組級安全培訓", "other": "通用及其他資料"}, "placeholders": {"onePerLine": "每行填寫一項", "oneQuestionPerLine": "每行填寫一個問題"}, "fields": {"type": "培訓類型編碼", "name": "配置名稱", "version": "版本", "status": "狀態", "passScore": "及格分數", "examMode": "考試模式", "summaryPoints": "複盤要點", "summaryChecklist": "考前清單", "employeeQuestions": "員工常見問題", "hrQuestions": "HR 常見問題"}, "status": {"draft": "草稿", "published": "已發佈", "archived": "已歸檔"}, "examMode": {"unified": "統一試卷", "perLevel": "按級別考試"}, "resourceTypes": {"questions": "內置題目", "guide": "指南資源", "document": "知識庫文件"}, "messages": {"loadFailed": "載入培訓配置失敗", "saveFailed": "儲存培訓配置失敗", "typeRequired": "請填寫培訓類型編碼和名稱", "invalidQuestions": "題目 JSON 必須是陣列", "questionSourceRequired": "請選擇培訓試題 PDF", "parseSuccess": "已解析 {count} 道題目,請複核後儲存", "parseFailed": "題庫解析失敗", "saved": "培訓配置已儲存", "deleted": "培訓配置已刪除"}
|
||||
}
|
||||
}
|
||||
@@ -1047,6 +1047,7 @@
|
||||
"progressPercent": "完成度",
|
||||
"stepNo": "步驟 {value}",
|
||||
"defaultLearnerName": "當前學員",
|
||||
"noContent": { "loading": "正在載入培訓內容...", "title": "暫無培訓內容", "description": "管理員尚未發布當前培訓配置,請稍後再試。" },
|
||||
"unknownDepartment": "待補充部門",
|
||||
"video": {
|
||||
"title": "第一步:觀看培訓影片",
|
||||
|
||||
@@ -4,6 +4,8 @@ import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
const rootDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const frontendPort = Number(process.env.HXOPS_FRONTEND_PORT || '8881')
|
||||
const apiProxyTarget = process.env.HXOPS_API_PROXY_TARGET || 'http://127.0.0.1:5052'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
@@ -14,12 +16,12 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 8881, // 前端开发端口,实际上我们会用 Nginx 反代,但本地开发先改这个方便
|
||||
port: frontendPort, // 默认 8881,允许本地通过环境变量覆盖,避免与其它仓库冲突
|
||||
strictPort: true, // 端口被占用时直接失败,由 start_local.ps1 先释放旧进程
|
||||
allowedHosts: ['hx.benl.cn'],
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:5052',
|
||||
target: apiProxyTarget,
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user