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))
|
||||
|
||||
Reference in new issue
Block a user