241 lines
9.1 KiB
Python
241 lines
9.1 KiB
Python
"""
|
|
backend/app/services/training_service.py
|
|
|
|
用途:封装新人培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
|
依赖:app.models.TrainingRecord/User、app.extensions.db、openpyxl。
|
|
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录并提供 HR 侧聚合结果。
|
|
"""
|
|
|
|
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 TrainingRecord, User
|
|
|
|
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
|
|
|
|
|
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 _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,
|
|
"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) -> Optional[TrainingRecord]:
|
|
"""查询指定用户当前培训记录。"""
|
|
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id)
|
|
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。
|
|
"""
|
|
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"))
|
|
passed = bool(payload.get("passed")) or (stage == "result" and score >= 90)
|
|
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
|
|
|
record = get_user_training_record(user.id)
|
|
if not record:
|
|
record = TrainingRecord(
|
|
user_id=user.id,
|
|
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.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) -> 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()
|
|
|
|
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
|
|
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
|