705 lines
28 KiB
Python
705 lines
28 KiB
Python
"""
|
||
backend/app/services/training_service.py
|
||
|
||
用途:封装员工培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||
依赖:app.models.TrainingRecord/User、app.extensions.db、openpyxl。
|
||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录,并为安全培训补齐考试模式、三级状态和版本号的 P0 持久化。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass
|
||
from datetime import date, datetime
|
||
from io import BytesIO
|
||
import re
|
||
from typing import Any, Iterable, Optional
|
||
|
||
from openpyxl import Workbook
|
||
from sqlalchemy import select
|
||
|
||
from app.core.errors import ValidationError
|
||
from app.extensions import db
|
||
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"}
|
||
VIDEO_ONLY_TRAINING_TYPES = {
|
||
"overseas_regulations",
|
||
"overseas_regulations_training",
|
||
"overseas_training",
|
||
}
|
||
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: 培训类型编码。
|
||
Returns:
|
||
默认培训版本字符串。
|
||
"""
|
||
return f"{training_type}-v1"
|
||
|
||
|
||
def _configured_training_types() -> set[str]:
|
||
"""读取数据库中已配置的培训类型编码,供进度接口动态校验。"""
|
||
from app.models import TrainingConfig
|
||
|
||
return {
|
||
str(training_type).strip()
|
||
for training_type in db.session.execute(select(TrainingConfig.training_type)).scalars()
|
||
if str(training_type or "").strip()
|
||
}
|
||
|
||
|
||
def _normalize_training_type(value: Any) -> str:
|
||
"""
|
||
校验并标准化培训类型。
|
||
|
||
Args:
|
||
value: 前端上传的培训类型编码,允许空值回退为 onboarding。
|
||
Returns:
|
||
已配置的培训类型编码。
|
||
"""
|
||
text = str(value or "onboarding").strip().lower() or "onboarding"
|
||
allowed = TRAINING_TYPES | _configured_training_types()
|
||
if text not in allowed:
|
||
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(allowed)})
|
||
return text
|
||
|
||
|
||
def _is_overseas_regulations_training(training_type: str) -> bool:
|
||
"""
|
||
判断培训类型是否为出国规章视频培训。
|
||
|
||
Args:
|
||
training_type: 已标准化的培训类型编码。
|
||
Returns:
|
||
是否应以完整观看视频作为一次培训完成。
|
||
"""
|
||
if training_type in VIDEO_ONLY_TRAINING_TYPES:
|
||
return True
|
||
published = get_published_config(training_type)
|
||
return "出国规章培训" in str((published or {}).get("name") or "")
|
||
|
||
|
||
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, Any]:
|
||
"""
|
||
根据安全培训当前阶段推导三级学习进度。
|
||
|
||
Args:
|
||
safety_stage: 安全培训阶段。允许 company / department / team / exam / result。
|
||
Returns:
|
||
company、department、team 三个级别的状态快照。
|
||
"""
|
||
progress: dict[str, Any] = {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, Any]:
|
||
"""
|
||
规范安全培训三级进度对象。
|
||
|
||
核心逻辑:先按当前阶段生成基准状态,再用前端已保存值做增量覆盖,确保缺字段时仍保持完整结构。
|
||
|
||
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 _is_safety_learning_complete(safety_progress: dict[str, Any], training_type: str) -> bool:
|
||
"""
|
||
按已发布安全培训配置校验三级资料是否均已完成。
|
||
|
||
用途:安全培训请求进入考试或结算阶段时,服务端不能信任前端阶段字段,必须以每项配置资料的完成记录为准。
|
||
参数约束:仅安全培训生效;未配置资料的级别视为无须学习,所有已配置资料必须在 resource_progress 中标记 completed=True。
|
||
"""
|
||
if training_type != "safety":
|
||
return True
|
||
published = get_published_config("safety")
|
||
learning_resources = [
|
||
resource for resource in (published or {}).get("resources") or []
|
||
if resource.get("resource_type") != "inline_questions"
|
||
and resource.get("training_level") in SAFETY_LEVEL_KEYS
|
||
]
|
||
resource_progress = safety_progress.get("resource_progress") or {}
|
||
return all(
|
||
isinstance(resource_progress.get(str(resource.get("id"))), dict)
|
||
and bool(resource_progress[str(resource["id"])].get("completed"))
|
||
for resource in learning_resources
|
||
)
|
||
|
||
|
||
def _assert_safety_exam_prerequisites(stage: str, safety_progress: dict[str, Any], training_type: str) -> None:
|
||
"""
|
||
拦截未完成三级学习的安全培训考试与结算请求。
|
||
|
||
用途:当客户端尝试保存 exam/result 阶段时阻止绕过学习流程,确保考试状态只能在三级资料完成后产生。
|
||
参数约束:仅 stage 为 exam 或 result 且 training_type 为 safety 时校验失败并抛出统一 ValidationError。
|
||
"""
|
||
if training_type == "safety" and stage in {"exam", "result"} and not _is_safety_learning_complete(safety_progress, training_type):
|
||
raise ValidationError("Complete all company, department, and team safety training materials before starting or submitting the exam")
|
||
|
||
|
||
def _parse_iso_date(value: Any) -> Optional[date]:
|
||
text = str(value or "").strip()
|
||
if not text:
|
||
return None
|
||
try:
|
||
return date.fromisoformat(text)
|
||
except ValueError as exc:
|
||
raise ValidationError("join_date must be YYYY-MM-DD", details={"field": "join_date"}) from exc
|
||
|
||
|
||
def _normalize_answer_details(value: Any) -> list[dict]:
|
||
if value in (None, ""):
|
||
return []
|
||
if not isinstance(value, list):
|
||
raise ValidationError("answer_details must be an array", details={"field": "answer_details"})
|
||
normalized: list[dict] = []
|
||
for index, item in enumerate(value):
|
||
if not isinstance(item, dict):
|
||
raise ValidationError(
|
||
"answer_details item must be an object",
|
||
details={"field": "answer_details", "index": index},
|
||
)
|
||
normalized.append(
|
||
{
|
||
"question_id": str(item.get("question_id") or item.get("questionId") or ""),
|
||
"selected_option_id": str(item.get("selected_option_id") or item.get("selectedOptionId") or ""),
|
||
"answer_text": str(item.get("answer_text") or item.get("answerText") or ""),
|
||
"correct": bool(item.get("correct", False)),
|
||
"score_ratio": float(item.get("score_ratio") or item.get("scoreRatio") or 0),
|
||
}
|
||
)
|
||
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}"
|
||
question_type = str(raw.get("type") or "single").strip().lower()
|
||
question_type = {
|
||
"choice": "single",
|
||
"select": "single",
|
||
"bool": "boolean",
|
||
"judgment": "boolean",
|
||
"judge": "boolean",
|
||
"判断": "boolean",
|
||
"判断题": "boolean",
|
||
"3": "boolean",
|
||
"blank": "fill",
|
||
"fill_blank": "fill",
|
||
"qa": "essay",
|
||
"question_answer": "essay",
|
||
"short_answer": "essay",
|
||
"问答": "essay",
|
||
"问答题": "essay",
|
||
"简答": "essay",
|
||
"简答题": "essay",
|
||
"4": "essay",
|
||
}.get(question_type, question_type)
|
||
if question_type not in {"single", "boolean", "fill", "essay"} or not prompt:
|
||
continue
|
||
if question_type in {"single", "boolean"} and not answer:
|
||
continue
|
||
try:
|
||
score_ratio = float(raw.get("score_ratio") or raw.get("scoreRatio") or 1)
|
||
except (TypeError, ValueError):
|
||
score_ratio = 1.0
|
||
score_ratio = max(0.0, score_ratio)
|
||
|
||
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": question_type,
|
||
"prompt": prompt,
|
||
"answer": answer,
|
||
"score_ratio": score_ratio,
|
||
"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 _normalize_text_answer(value: Any) -> str:
|
||
"""
|
||
规范文本题答案以进行无格式差异的自动判定。
|
||
|
||
用途:填空和问答题有标准答案时忽略空白与大小写,避免录入格式造成误判。
|
||
Args:
|
||
value: 学员作答或题库标准答案。
|
||
Returns:
|
||
删除全部空白并转换为小写后的文本。
|
||
"""
|
||
return re.sub(r"[\s\u3000、,,;;。..!!??::()()【】\[\]{}\"'“”‘’\-—_]+", "", str(value or "")).casefold()
|
||
|
||
|
||
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] = []
|
||
total_score_ratio = sum(float(question.get("score_ratio") or 0) for question in question_bank)
|
||
earned_score_ratio = 0.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()
|
||
answer_text = str(item.get("answer_text") or item.get("answerText") or "")
|
||
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})
|
||
question_type = str(question["type"])
|
||
if question_type in {"fill", "essay"}:
|
||
normalized_answer = _normalize_text_answer(answer_text)
|
||
normalized_standard_answer = _normalize_text_answer(question["answer"])
|
||
if normalized_standard_answer:
|
||
earned_ratio = 1.0 if normalized_answer == normalized_standard_answer else 0.0
|
||
elif not normalized_answer:
|
||
earned_ratio = 0.0
|
||
else:
|
||
earned_ratio = 1.0 if len(answer_text.strip()) > 20 else 0.8
|
||
is_correct = earned_ratio == 1.0
|
||
else:
|
||
earned_ratio = 1.0 if selected_option_id == str(question["answer"]) else 0.0
|
||
is_correct = bool(earned_ratio)
|
||
question_score_ratio = float(question.get("score_ratio") or 0)
|
||
earned_score_ratio += question_score_ratio * earned_ratio
|
||
normalized.append(
|
||
{
|
||
"question_id": question_id,
|
||
"selected_option_id": selected_option_id,
|
||
"answer_text": answer_text,
|
||
"correct": is_correct,
|
||
"score_ratio": earned_ratio,
|
||
}
|
||
)
|
||
|
||
score = round((earned_score_ratio / total_score_ratio) * 100) if total_score_ratio > 0 else 0
|
||
return normalized, score, score >= pass_score
|
||
|
||
|
||
def _derive_status(record: TrainingRecord) -> str:
|
||
if bool(record.passed):
|
||
return "passed"
|
||
if record.stage == "result":
|
||
return "failed"
|
||
return "in_progress"
|
||
|
||
|
||
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,
|
||
"join_date": record.join_date.isoformat() if record.join_date else None,
|
||
"stage": record.stage,
|
||
"current_question_index": int(record.current_question_index or 0),
|
||
"score": int(record.score or 0),
|
||
"passed": bool(record.passed),
|
||
"attempt_count": int(record.attempt_count or 0),
|
||
"answer_details": list(record.answer_details or []),
|
||
"started_at": record.started_at.isoformat() if record.started_at else None,
|
||
"completion_time": record.completion_time.isoformat() if record.completion_time else None,
|
||
"created_at": record.created_at.isoformat() if record.created_at else None,
|
||
"updated_at": record.updated_at.isoformat() if record.updated_at else None,
|
||
"status": _derive_status(record),
|
||
}
|
||
|
||
|
||
def _apply_user_snapshot(record: TrainingRecord, user: User) -> None:
|
||
record.employee_id = (user.employee_id or "").strip() or None
|
||
record.name = (user.real_name or "").strip() or (user.username or "").strip() or None
|
||
record.department = (user.department or "").strip() or None
|
||
|
||
|
||
def get_user_training_record(user_id: int, training_type: str = "onboarding") -> Optional[TrainingRecord]:
|
||
"""查询指定用户当前培训记录。"""
|
||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id, TrainingRecord.training_type == training_type)
|
||
return db.session.execute(stmt).scalar_one_or_none()
|
||
|
||
|
||
def upsert_user_training_record(user: User, payload: dict[str, Any]) -> TrainingRecord:
|
||
"""
|
||
保存当前用户培训进度。
|
||
|
||
Args:
|
||
user: 当前登录用户。
|
||
payload: 前端上传的培训进度快照。
|
||
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)})
|
||
|
||
current_question_index = int(payload.get("current_question_index") or payload.get("currentQuestionIndex") or 0)
|
||
score = int(payload.get("score") or 0)
|
||
attempt_count = int(payload.get("attempt_count") or payload.get("attemptCount") or 0)
|
||
if current_question_index < 0:
|
||
raise ValidationError("current_question_index must be >= 0", details={"field": "current_question_index"})
|
||
if score < 0:
|
||
raise ValidationError("score must be >= 0", details={"field": "score"})
|
||
if attempt_count < 0:
|
||
raise ValidationError("attempt_count must be >= 0", details={"field": "attempt_count"})
|
||
|
||
answer_details = _normalize_answer_details(payload.get("answer_details") or payload.get("answerDetails"))
|
||
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)
|
||
|
||
if stage == "result" and question_bank and not answer_details and not _is_overseas_regulations_training(training_type):
|
||
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,
|
||
)
|
||
_assert_safety_exam_prerequisites(stage, safety_progress, training_type)
|
||
|
||
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(),
|
||
)
|
||
db.session.add(record)
|
||
elif join_date:
|
||
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
|
||
record.passed = passed
|
||
record.attempt_count = attempt_count
|
||
record.answer_details = answer_details
|
||
|
||
if stage == "result":
|
||
record.completion_time = datetime.utcnow()
|
||
if not record.started_at:
|
||
record.started_at = datetime.utcnow()
|
||
else:
|
||
record.completion_time = None
|
||
if stage in {"summary", "exam"} and not record.started_at:
|
||
record.started_at = datetime.utcnow()
|
||
|
||
db.session.commit()
|
||
return record
|
||
|
||
|
||
@dataclass
|
||
class TrainingListResult:
|
||
records: list[TrainingRecord]
|
||
total: int
|
||
|
||
|
||
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()
|
||
|
||
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:
|
||
record_status = _derive_status(record)
|
||
if keyword_text:
|
||
searchable = " ".join(
|
||
[
|
||
str(record.name or ""),
|
||
str(record.employee_id or ""),
|
||
]
|
||
).lower()
|
||
if keyword_text not in searchable:
|
||
continue
|
||
if department_text and department_text != "all" and (record.department or "") != department_text:
|
||
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))
|
||
|
||
|
||
def summarize_training_records(records: Iterable[TrainingRecord]) -> dict[str, int]:
|
||
"""统计培训记录聚合指标。"""
|
||
data = list(records)
|
||
total = len(data)
|
||
passed = sum(1 for item in data if _derive_status(item) == "passed")
|
||
failed = sum(1 for item in data if _derive_status(item) == "failed")
|
||
in_progress = sum(1 for item in data if _derive_status(item) == "in_progress")
|
||
scored_items = [int(item.score or 0) for item in data if item.score is not None]
|
||
average_score = round(sum(scored_items) / len(scored_items)) if scored_items else 0
|
||
return {
|
||
"total": total,
|
||
"passed": passed,
|
||
"failed": failed,
|
||
"in_progress": in_progress,
|
||
"pass_rate": round((passed / total) * 100) if total else 0,
|
||
"average_score": average_score,
|
||
}
|
||
|
||
|
||
def export_training_records_excel(records: Iterable[TrainingRecord]) -> tuple[bytes, str]:
|
||
"""将培训记录导出为 Excel 文件。"""
|
||
workbook = Workbook()
|
||
worksheet = workbook.active
|
||
worksheet.title = "training"
|
||
worksheet.append(["入职日期", "完成日期", "培训类型", "部门", "姓名", "工号", "分数", "考试次数", "状态"])
|
||
|
||
for record in records:
|
||
worksheet.append(
|
||
[
|
||
record.join_date.isoformat() if record.join_date else "",
|
||
record.completion_time.date().isoformat() if record.completion_time else "",
|
||
record.training_type or "",
|
||
record.department or "",
|
||
record.name or "",
|
||
record.employee_id or "",
|
||
record.score if record.score is not None else "",
|
||
record.attempt_count or 0,
|
||
{"passed": "已通过", "failed": "未通过", "in_progress": "进行中"}.get(_derive_status(record), _derive_status(record)),
|
||
]
|
||
)
|
||
|
||
buffer = BytesIO()
|
||
workbook.save(buffer)
|
||
filename = f"training_records_{datetime.utcnow().date().isoformat()}.xlsx"
|
||
return buffer.getvalue(), filename
|