""" backend/app/services/training_config_service.py 用途:提供培训配置 CRUD、三级资料绑定与员工培训知识库候选资料查询。 依赖:培训、AgentGuide 与知识库 ORM 模型,以及统一业务异常。 逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照; 同时在 settings 中统一维护培训进度项与学员侧文案配置。 """ from __future__ import annotations from datetime import datetime from typing import Any import re 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"} GENERIC_PROGRESS_STAGES = ("video", "summary", "exam", "result") SAFETY_PROGRESS_STAGES = ("company", "department", "team", "exam") TRAINING_TYPE_ALIASES = { "入职培训": "onboarding", "新人培训": "onboarding", "安全培训": "safety", } DEFAULT_TRAINING_SETTINGS: dict[str, dict[str, Any]] = { "onboarding": { "progress_items": [ {"stage": "video", "label": "观看视频"}, {"stage": "summary", "label": "复盘知识点"}, {"stage": "exam", "label": "逐题考试"}, {"stage": "result", "label": "结算结果"}, ], "progress_hint_text": "按 HR 要求完成视频、知识点、考试三个环节后才能视为完成。", "step_intro_text": "第一步:观看培训视频\n员工先完成入职培训视频学习,再进入知识点复盘和考试环节。", }, "safety": { "progress_items": [ {"stage": "company", "label": "公司级安全培训"}, {"stage": "department", "label": "部门级安全培训"}, {"stage": "team", "label": "班组级安全培训"}, {"stage": "exam", "label": "统一考试"}, ], "progress_hint_text": "按国家安全生产法要求,新员工须依次完成公司级、部门级、班组级三级安全教育。学完三级的全部资料或视频后,进入 1 次统一考试,90 分及格方可结业。", "step_intro_text": "第一步:完成公司级安全教育\n员工需先完成公司级安全教育资料学习,再依次进入部门级、班组级和统一考试环节。", }, } def _normalize_type_code(value: Any) -> str: """ 校验并标准化培训类型编码。 用途:管理端新增或员工端读取培训类型时统一使用稳定编码,避免名称变化影响培训记录关联。 Args: value: 培训类型编码;兼容历史中文别名。 Returns: 小写的合法类型编码。 """ text = TRAINING_TYPE_ALIASES.get(str(value or "").strip(), str(value or "").strip().lower()) if not re.fullmatch(r"[a-z][a-z0-9_-]{0,49}", text): raise ValidationError("training_type is invalid", details={"field": "training_type"}) return text def list_training_type_codes() -> list[dict[str, str]]: """返回已发布培训类型的编码与名称,供员工端动态加载培训入口。""" configs = db.session.execute( select(TrainingConfig.training_type, TrainingConfig.name) .where(TrainingConfig.status == "published") .order_by(TrainingConfig.training_type) ).all() return [{"code": type_code, "name": str(name or "").strip()} for type_code, name in configs] 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 _allowed_progress_stages(training_type: str) -> tuple[str, ...]: return SAFETY_PROGRESS_STAGES if training_type == "safety" else GENERIC_PROGRESS_STAGES def _normalize_copy_text(field: str, value: Any) -> str | None: """ 清洗培训工作区的可编辑长文本字段。 用途:统一校验进度说明和步骤引导文案长度,兼容历史空值读写逻辑。 参数约束:允许空值;若传入非空内容则去首尾空白且长度不得超过 500 字符。 """ if value is None: return None text = str(value).strip() if not text: return None if len(text) > 500: raise ValidationError(f"{field} exceeds max length", details={"field": field, "max_length": 500}) return text def _normalize_progress_items(value: Any, training_type: str) -> list[dict[str, str]]: """ 规范培训进度项配置。 用途:让后台保存的进度项始终携带稳定 stage 编码,供学员侧按配置动态渲染流程卡片。 参数约束:允许空数组;每项必须包含唯一 stage 和非空 label。 """ if value in (None, ""): return [] if not isinstance(value, list): raise ValidationError("progress_items must be an array", details={"field": "settings.progress_items"}) allowed_stages = set(_allowed_progress_stages(training_type)) seen_stages: set[str] = set() normalized: list[dict[str, str]] = [] for index, item in enumerate(value): if not isinstance(item, dict): raise ValidationError("progress_items item must be an object", details={"field": "settings.progress_items", "index": index}) stage = str(item.get("stage") or item.get("key") or "").strip() label = str(item.get("label") or item.get("title") or "").strip() if stage not in allowed_stages: raise ValidationError( "progress_items stage is invalid", details={"field": "settings.progress_items.stage", "index": index, "allowed": sorted(allowed_stages)}, ) if stage in seen_stages: raise ValidationError("progress_items contains duplicate stage", details={"field": "settings.progress_items.stage", "index": index}) if not label: raise ValidationError("progress_items label is required", details={"field": "settings.progress_items.label", "index": index}) if len(label) > 100: raise ValidationError("progress_items label exceeds max length", details={"field": "settings.progress_items.label", "index": index, "max_length": 100}) seen_stages.add(stage) normalized.append({"stage": stage, "label": label}) return normalized def _normalize_settings(training_type: str, value: Any, *, include_defaults: bool) -> dict[str, Any]: """ 规范培训配置 settings 并按需注入存量默认值。 用途:统一维护发布配置中的工作区文本与进度项,避免管理端与学员端各自拼装字段。 核心逻辑:先保留历史设置,再清洗新增字段;对 onboarding / safety 可按读取场景补默认值,保证旧配置展示不回退为空。 """ settings = dict(value) if isinstance(value, dict) else {} normalized = {**settings} if "progress_items" in settings: normalized["progress_items"] = _normalize_progress_items(settings.get("progress_items"), training_type) elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS: normalized["progress_items"] = [dict(item) for item in DEFAULT_TRAINING_SETTINGS[training_type]["progress_items"]] progress_hint_text = _normalize_copy_text("settings.progress_hint_text", settings.get("progress_hint_text")) step_intro_text = _normalize_copy_text("settings.step_intro_text", settings.get("step_intro_text")) if progress_hint_text is not None: normalized["progress_hint_text"] = progress_hint_text elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS: normalized["progress_hint_text"] = DEFAULT_TRAINING_SETTINGS[training_type]["progress_hint_text"] if step_intro_text is not None: normalized["step_intro_text"] = step_intro_text elif include_defaults and training_type in DEFAULT_TRAINING_SETTINGS: normalized["step_intro_text"] = DEFAULT_TRAINING_SETTINGS[training_type]["step_intro_text"] return normalized 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}/training-preview-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]: settings = _normalize_settings(config.training_type, config.settings, include_defaults=True) return { "id": config.id, "training_type": config.training_type, "name": config.name, "version": config.version, "status": config.status, "pass_score": config.pass_score, "settings": settings, "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": str(item.get("title") or "").strip() or None, "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 = _normalize_type_code(raw_training_type) name = str(data.get("name") or config.name or "").strip() version = str(data.get("version") or config.version or "").strip() if not training_type: raise ValidationError("training_type is invalid", details={"field": "training_type"}) 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 = _normalize_settings(training_type, data["settings"], include_defaults=False) 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]: """ 更新培训配置并保持未替换资料绑定的稳定主键。 用途:管理端保存配置时复用既有资料行,避免员工安全培训进度按资料绑定 ID 记录后失去关联。 Args: config_id: 要更新的培训配置 ID。 data: 管理端提交的完整配置;既有资料必须携带且仅能携带当前配置下的 `id`。 user_id: 当前管理员 ID,可为空。 Returns: 更新后的培训配置序列化结果。 """ 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"}) existing_resources = {resource.id: resource for resource in config.resources} submitted_resource_ids: set[int] = set() updated_resources: list[TrainingConfigResource] = [] for item in data["resources"]: validated = _validate_resource(item) resource_id = item.get("id") if resource_id is None: updated_resources.append(TrainingConfigResource(**validated)) continue parsed_resource_id = _required_int(resource_id, "resources.id") if parsed_resource_id in submitted_resource_ids: raise ValidationError("resources contains duplicate id", details={"field": "resources.id"}) submitted_resource_ids.add(parsed_resource_id) resource = existing_resources.get(parsed_resource_id) if not resource: raise ValidationError("Training config resource not found", details={"field": "resources.id"}) for field, value in validated.items(): setattr(resource, field, value) updated_resources.append(resource) config.resources = updated_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: try: normalized_type = _normalize_type_code(training_type) except ValidationError: 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') ], }