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