feat(安全培训): 新增员工安全培训相关功能
This commit is contained in:
1 parent
cbc3cb959f
commit
8e5c57790c
50 files changed
+3769
-87
No files matched your search
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/training_service.py
|
||||
|
||||
用途:封装新人培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||||
用途:封装员工培训记录的序列化、进度保存、列表筛选、统计与导出能力。
|
||||
依赖:app.models.TrainingRecord/User、app.extensions.db、openpyxl。
|
||||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录并提供 HR 侧聚合结果。
|
||||
逻辑:API 层仅做鉴权与参数解析;本模块负责把前端培训状态转成数据库记录,并为安全培训补齐考试模式、三级状态和版本号的 P0 持久化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,9 +18,144 @@ from sqlalchemy import select
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import TrainingRecord, User
|
||||
from app.models import Agent, TrainingRecord, User
|
||||
from app.services.training_config_service import get_published_config
|
||||
|
||||
TRAINING_STAGES = {"video", "summary", "exam", "result"}
|
||||
TRAINING_TYPES = {"onboarding", "safety"}
|
||||
TRAINING_EXAM_MODES = {"unified", "per_level"}
|
||||
SAFETY_STAGES = {"company", "department", "team", "exam", "result"}
|
||||
SAFETY_LEVEL_KEYS = ("company", "department", "team")
|
||||
DEFAULT_PASS_SCORE = 90
|
||||
|
||||
|
||||
def _default_training_version(training_type: str) -> str:
|
||||
"""
|
||||
返回培训类型对应的默认版本号。
|
||||
|
||||
Args:
|
||||
training_type: 培训类型。当前仅允许 onboarding / safety。
|
||||
Returns:
|
||||
默认培训版本字符串。
|
||||
"""
|
||||
return "safety-v1" if training_type == "safety" else "onboarding-v1"
|
||||
|
||||
|
||||
def _normalize_training_type(value: Any) -> str:
|
||||
"""
|
||||
校验并标准化培训类型。
|
||||
|
||||
Args:
|
||||
value: 前端上传的培训类型,允许空值回退为 onboarding。
|
||||
Returns:
|
||||
合法的培训类型字符串。
|
||||
"""
|
||||
text = str(value or "onboarding").strip() or "onboarding"
|
||||
if text not in TRAINING_TYPES:
|
||||
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(TRAINING_TYPES)})
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_training_version(value: Any, training_type: str) -> str:
|
||||
"""
|
||||
规范培训版本号,未传时按培训类型补默认值。
|
||||
|
||||
Args:
|
||||
value: 前端上传的版本号。
|
||||
training_type: 已标准化的培训类型,用于选择默认版本。
|
||||
Returns:
|
||||
培训版本号。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
return text or _default_training_version(training_type)
|
||||
|
||||
|
||||
def _normalize_exam_mode(value: Any) -> str:
|
||||
"""
|
||||
校验考试模式是否合法。
|
||||
|
||||
Args:
|
||||
value: 前端上传的考试模式,首期支持 unified / per_level。
|
||||
Returns:
|
||||
合法的考试模式。
|
||||
"""
|
||||
text = str(value or "unified").strip() or "unified"
|
||||
if text not in TRAINING_EXAM_MODES:
|
||||
raise ValidationError("exam_mode is invalid", details={"field": "exam_mode", "allowed": sorted(TRAINING_EXAM_MODES)})
|
||||
return text
|
||||
|
||||
|
||||
def _build_default_safety_progress(safety_stage: str) -> dict[str, str]:
|
||||
"""
|
||||
根据安全培训当前阶段推导三级学习进度。
|
||||
|
||||
Args:
|
||||
safety_stage: 安全培训阶段。允许 company / department / team / exam / result。
|
||||
Returns:
|
||||
company、department、team 三个级别的状态快照。
|
||||
"""
|
||||
progress: dict[str, str] = {key: "pending" for key in SAFETY_LEVEL_KEYS}
|
||||
if safety_stage == "company":
|
||||
progress["company"] = "active"
|
||||
return progress
|
||||
if safety_stage == "department":
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "active"
|
||||
return progress
|
||||
if safety_stage == "team":
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "completed"
|
||||
progress["team"] = "active"
|
||||
return progress
|
||||
progress["company"] = "completed"
|
||||
progress["department"] = "completed"
|
||||
progress["team"] = "completed"
|
||||
return progress
|
||||
|
||||
|
||||
def _normalize_safety_stage(value: Any) -> str:
|
||||
"""
|
||||
校验安全培训阶段。
|
||||
|
||||
Args:
|
||||
value: 前端上传的安全培训阶段。
|
||||
Returns:
|
||||
合法的安全培训阶段字符串。
|
||||
"""
|
||||
text = str(value or "company").strip() or "company"
|
||||
if text not in SAFETY_STAGES:
|
||||
raise ValidationError("safety_stage is invalid", details={"field": "safety_stage", "allowed": sorted(SAFETY_STAGES)})
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_safety_progress(value: Any, safety_stage: str) -> dict[str, str]:
|
||||
"""
|
||||
规范安全培训三级进度对象。
|
||||
|
||||
核心逻辑:先按当前阶段生成基准状态,再用前端已保存值做增量覆盖,确保缺字段时仍保持完整结构。
|
||||
|
||||
Args:
|
||||
value: 前端上传的三级进度对象。
|
||||
safety_stage: 当前安全培训阶段,用于补齐默认状态。
|
||||
Returns:
|
||||
标准化后的三级进度对象。
|
||||
"""
|
||||
if value in (None, ""):
|
||||
return _build_default_safety_progress(safety_stage)
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError("safety_progress must be an object", details={"field": "safety_progress"})
|
||||
normalized = _build_default_safety_progress(safety_stage)
|
||||
for key in SAFETY_LEVEL_KEYS:
|
||||
current = str(value.get(key) or "").strip()
|
||||
if current:
|
||||
normalized[key] = current
|
||||
|
||||
# 保留资源级别的进度记录
|
||||
resource_progress = value.get("resource_progress")
|
||||
if isinstance(resource_progress, dict):
|
||||
normalized["resource_progress"] = resource_progress
|
||||
|
||||
return normalized
|
||||
|
||||
|
||||
def _parse_iso_date(value: Any) -> Optional[date]:
|
||||
@@ -55,6 +190,158 @@ def _normalize_answer_details(value: Any) -> list[dict]:
|
||||
return normalized
|
||||
|
||||
|
||||
def _as_record(value: Any) -> dict[str, Any]:
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _normalize_pass_score(value: Any) -> int:
|
||||
parsed = int(value) if str(value or "").strip() else DEFAULT_PASS_SCORE
|
||||
return max(0, min(100, parsed))
|
||||
|
||||
|
||||
def _normalize_question_bank(value: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
规范后端训练题库结构,供服务端判卷使用。
|
||||
|
||||
Args:
|
||||
value: Agent extra_config.training_config 中的 question_bank。
|
||||
Returns:
|
||||
仅保留判卷所需字段的题库列表。
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for index, item in enumerate(value):
|
||||
raw = _as_record(item)
|
||||
prompt = str(raw.get("prompt") or "").strip()
|
||||
answer = str(raw.get("answer") or "").strip()
|
||||
question_id = str(raw.get("id") or "").strip() or f"q{index + 1}"
|
||||
if not prompt or not answer:
|
||||
continue
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
raw_options = raw.get("options")
|
||||
if isinstance(raw_options, list):
|
||||
for option_index, option in enumerate(raw_options):
|
||||
if isinstance(option, str):
|
||||
label = option.strip()
|
||||
if not label:
|
||||
continue
|
||||
options.append(
|
||||
{
|
||||
"id": str(chr(97 + option_index)),
|
||||
"label": label,
|
||||
}
|
||||
)
|
||||
continue
|
||||
option_raw = _as_record(option)
|
||||
option_id = str(option_raw.get("id") or "").strip() or str(chr(97 + option_index))
|
||||
label = str(option_raw.get("label") or "").strip()
|
||||
if option_id and label:
|
||||
options.append({"id": option_id, "label": label})
|
||||
|
||||
normalized.append(
|
||||
{
|
||||
"id": question_id,
|
||||
"type": "boolean" if str(raw.get("type") or "").strip() == "boolean" else "single",
|
||||
"prompt": prompt,
|
||||
"answer": answer,
|
||||
"options": options,
|
||||
"explanation": str(raw.get("explanation") or "").strip(),
|
||||
}
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def _resolve_training_runtime_config(agent_id: Any, training_type: str) -> tuple[int, list[dict[str, Any]]]:
|
||||
"""
|
||||
读取培训 Agent 的运行时题库配置。
|
||||
|
||||
核心逻辑:优先从 Agent.extra_config.training_config 读取正式题库和及格线,
|
||||
兼容历史顶层字段,供服务端判卷使用。
|
||||
|
||||
Args:
|
||||
agent_id: 当前培训 Agent ID。必须能定位到真实 Agent 配置。
|
||||
Returns:
|
||||
(pass_score, question_bank)
|
||||
"""
|
||||
published = get_published_config(training_type)
|
||||
if published:
|
||||
settings = _as_record(published.get("settings"))
|
||||
configured_questions = [
|
||||
question
|
||||
for resource in published.get("resources") or []
|
||||
if resource.get("resource_type") == "inline_questions"
|
||||
for question in resource.get("inline_questions") or []
|
||||
]
|
||||
questions = configured_questions or settings.get("questions") or settings.get("question_bank")
|
||||
question_bank = _normalize_question_bank(questions)
|
||||
if question_bank:
|
||||
return _normalize_pass_score(published.get("pass_score")), question_bank
|
||||
|
||||
if agent_id in (None, ""):
|
||||
return DEFAULT_PASS_SCORE, []
|
||||
|
||||
try:
|
||||
parsed_agent_id = int(agent_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("training agent is invalid", details={"field": "agent_id"}) from exc
|
||||
agent = db.session.get(Agent, parsed_agent_id)
|
||||
if not agent:
|
||||
raise ValidationError("training agent is invalid", details={"field": "agent_id"})
|
||||
|
||||
extra_config = _as_record(agent.extra_config)
|
||||
training_config = _as_record(extra_config.get("training_config"))
|
||||
merged_config = {
|
||||
**extra_config,
|
||||
**training_config,
|
||||
}
|
||||
pass_score = _normalize_pass_score(merged_config.get("pass_score") or merged_config.get("passScore") or merged_config.get("training_pass_score"))
|
||||
question_bank = _normalize_question_bank(merged_config.get("question_bank") or merged_config.get("questionBank"))
|
||||
return pass_score, question_bank
|
||||
|
||||
|
||||
def _grade_answer_details(answer_details: list[dict], question_bank: list[dict[str, Any]], pass_score: int) -> tuple[list[dict], int, bool]:
|
||||
"""
|
||||
基于后端题库对答题记录重新判卷。
|
||||
|
||||
Args:
|
||||
answer_details: 前端上传的答题记录,仅信任 question_id / selected_option_id。
|
||||
question_bank: 后端题库真相源。
|
||||
pass_score: 当前培训及格线。
|
||||
Returns:
|
||||
(重新标记 correct 后的答案明细, 百分制分数, 是否通过)
|
||||
"""
|
||||
if not question_bank:
|
||||
raise ValidationError("training question bank is not configured", details={"field": "agent_id"})
|
||||
|
||||
question_lookup = {str(item["id"]): item for item in question_bank}
|
||||
normalized: list[dict] = []
|
||||
correct_count = 0
|
||||
for index, item in enumerate(answer_details):
|
||||
question_id = str(item.get("question_id") or item.get("questionId") or "").strip()
|
||||
selected_option_id = str(item.get("selected_option_id") or item.get("selectedOptionId") or "").strip()
|
||||
if not question_id:
|
||||
raise ValidationError("answer_details item must include question_id", details={"field": "answer_details", "index": index})
|
||||
question = question_lookup.get(question_id)
|
||||
if not question:
|
||||
raise ValidationError("answer_details question_id is invalid", details={"field": "answer_details", "index": index, "question_id": question_id})
|
||||
is_correct = selected_option_id == str(question["answer"])
|
||||
if is_correct:
|
||||
correct_count += 1
|
||||
normalized.append(
|
||||
{
|
||||
"question_id": question_id,
|
||||
"selected_option_id": selected_option_id,
|
||||
"correct": is_correct,
|
||||
}
|
||||
)
|
||||
|
||||
score = round((correct_count / len(question_bank)) * 100) if question_bank else 0
|
||||
return normalized, score, score >= pass_score
|
||||
|
||||
|
||||
def _derive_status(record: TrainingRecord) -> str:
|
||||
if bool(record.passed):
|
||||
return "passed"
|
||||
@@ -68,6 +355,11 @@ def serialize_training_record(record: TrainingRecord) -> dict[str, Any]:
|
||||
return {
|
||||
"id": record.id,
|
||||
"user_id": record.user_id,
|
||||
"training_type": record.training_type,
|
||||
"training_version": record.training_version,
|
||||
"exam_mode": record.exam_mode,
|
||||
"safety_stage": record.safety_stage,
|
||||
"safety_progress": dict(record.safety_progress or {}),
|
||||
"employee_id": record.employee_id,
|
||||
"name": record.name,
|
||||
"department": record.department,
|
||||
@@ -92,9 +384,9 @@ def _apply_user_snapshot(record: TrainingRecord, user: User) -> None:
|
||||
record.department = (user.department or "").strip() or None
|
||||
|
||||
|
||||
def get_user_training_record(user_id: int) -> Optional[TrainingRecord]:
|
||||
def get_user_training_record(user_id: int, training_type: str = "onboarding") -> Optional[TrainingRecord]:
|
||||
"""查询指定用户当前培训记录。"""
|
||||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id)
|
||||
stmt = select(TrainingRecord).where(TrainingRecord.user_id == user_id, TrainingRecord.training_type == training_type)
|
||||
return db.session.execute(stmt).scalar_one_or_none()
|
||||
|
||||
|
||||
@@ -108,6 +400,13 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
Returns:
|
||||
已保存的 TrainingRecord。
|
||||
"""
|
||||
training_type = _normalize_training_type(payload.get("training_type") or payload.get("type") or "onboarding")
|
||||
agent_id = payload.get("agent_id") or payload.get("agentId")
|
||||
training_version = _normalize_training_version(
|
||||
payload.get("training_version") or payload.get("trainingVersion"),
|
||||
training_type,
|
||||
)
|
||||
exam_mode = _normalize_exam_mode(payload.get("exam_mode") or payload.get("examMode") or "unified")
|
||||
stage = str(payload.get("stage") or "video").strip() or "video"
|
||||
if stage not in TRAINING_STAGES:
|
||||
raise ValidationError("stage is invalid", details={"field": "stage", "allowed": sorted(TRAINING_STAGES)})
|
||||
@@ -123,13 +422,35 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
raise ValidationError("attempt_count must be >= 0", details={"field": "attempt_count"})
|
||||
|
||||
answer_details = _normalize_answer_details(payload.get("answer_details") or payload.get("answerDetails"))
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= 90)
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
pass_score, question_bank = _resolve_training_runtime_config(agent_id, training_type)
|
||||
if agent_id not in (None, "") and answer_details and not question_bank:
|
||||
raise ValidationError("training question bank is not configured", details={"field": "agent_id"})
|
||||
if question_bank and answer_details:
|
||||
answer_details, score, passed = _grade_answer_details(answer_details, question_bank, pass_score)
|
||||
else:
|
||||
passed = bool(payload.get("passed")) or (stage == "result" and score >= pass_score)
|
||||
|
||||
record = get_user_training_record(user.id)
|
||||
if stage == "result" and question_bank and not answer_details:
|
||||
raise ValidationError("answer_details is required when submitting result", details={"field": "answer_details"})
|
||||
join_date = _parse_iso_date(payload.get("join_date") or payload.get("joinDate"))
|
||||
safety_stage = None
|
||||
safety_progress = None
|
||||
if training_type == "safety":
|
||||
safety_stage = _normalize_safety_stage(payload.get("safety_stage") or payload.get("safetyStage") or "company")
|
||||
safety_progress = _normalize_safety_progress(
|
||||
payload.get("safety_progress") or payload.get("safetyProgress"),
|
||||
safety_stage,
|
||||
)
|
||||
|
||||
record = get_user_training_record(user.id, training_type)
|
||||
if not record:
|
||||
record = TrainingRecord(
|
||||
user_id=user.id,
|
||||
training_type=training_type,
|
||||
training_version=training_version,
|
||||
exam_mode=exam_mode,
|
||||
safety_stage=safety_stage,
|
||||
safety_progress=safety_progress,
|
||||
join_date=join_date or date.today(),
|
||||
started_at=datetime.utcnow(),
|
||||
)
|
||||
@@ -138,6 +459,10 @@ def upsert_user_training_record(user: User, payload: dict[str, Any]) -> Training
|
||||
record.join_date = join_date
|
||||
|
||||
_apply_user_snapshot(record, user)
|
||||
record.training_version = training_version
|
||||
record.exam_mode = exam_mode
|
||||
record.safety_stage = safety_stage
|
||||
record.safety_progress = safety_progress
|
||||
record.stage = stage
|
||||
record.current_question_index = current_question_index
|
||||
record.score = score
|
||||
@@ -164,7 +489,13 @@ class TrainingListResult:
|
||||
total: int
|
||||
|
||||
|
||||
def list_training_records(*, keyword: str | None = None, department: str | None = None, status: str | None = None) -> TrainingListResult:
|
||||
def list_training_records(
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
department: str | None = None,
|
||||
status: str | None = None,
|
||||
training_type: str | None = None,
|
||||
) -> TrainingListResult:
|
||||
"""按筛选条件列出培训记录。"""
|
||||
query = db.session.query(TrainingRecord).order_by(TrainingRecord.updated_at.desc(), TrainingRecord.id.desc())
|
||||
records = query.all()
|
||||
@@ -172,6 +503,7 @@ def list_training_records(*, keyword: str | None = None, department: str | None
|
||||
keyword_text = str(keyword or "").strip().lower()
|
||||
department_text = str(department or "").strip()
|
||||
status_text = str(status or "").strip()
|
||||
type_text = str(training_type or "").strip()
|
||||
|
||||
filtered: list[TrainingRecord] = []
|
||||
for record in records:
|
||||
@@ -189,6 +521,8 @@ def list_training_records(*, keyword: str | None = None, department: str | None
|
||||
continue
|
||||
if status_text and status_text != "all" and record_status != status_text:
|
||||
continue
|
||||
if type_text and type_text != "all" and record.training_type != type_text:
|
||||
continue
|
||||
filtered.append(record)
|
||||
|
||||
return TrainingListResult(records=filtered, total=len(filtered))
|
||||
|
||||
Reference in new issue
Block a user