575 lines
22 KiB
Python
575 lines
22 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
|
|
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"}
|
|
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, 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 _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 ""),
|
|
"correct": bool(item.get("correct", False)),
|
|
}
|
|
)
|
|
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"
|
|
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:
|
|
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(),
|
|
)
|
|
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.department or "",
|
|
record.name or "",
|
|
record.employee_id or "",
|
|
record.score if record.score is not None else "",
|
|
record.attempt_count or 0,
|
|
_derive_status(record),
|
|
]
|
|
)
|
|
|
|
buffer = BytesIO()
|
|
workbook.save(buffer)
|
|
filename = f"training_records_{datetime.utcnow().date().isoformat()}.xlsx"
|
|
return buffer.getvalue(), filename
|