238 lines
11 KiB
Python
238 lines
11 KiB
Python
"""
|
|
用途:提供培训配置 CRUD、三级资料绑定与员工培训知识库候选资料查询。
|
|
依赖:培训、AgentGuide 与知识库 ORM 模型,以及统一业务异常。
|
|
逻辑:管理端保存发布配置;候选与保存阶段双重限制知识库资料来源,员工端读取发布快照。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
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"}
|
|
TRAINING_TYPE_ALIASES = {
|
|
"入职培训": "onboarding",
|
|
"新人培训": "onboarding",
|
|
"安全培训": "safety",
|
|
}
|
|
|
|
|
|
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 _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}/source-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]:
|
|
return {
|
|
"id": config.id,
|
|
"training_type": config.training_type,
|
|
"name": config.name,
|
|
"version": config.version,
|
|
"status": config.status,
|
|
"pass_score": config.pass_score,
|
|
"settings": config.settings or {},
|
|
"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": item.get("title"), "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 = TRAINING_TYPE_ALIASES.get(raw_training_type, raw_training_type.lower())
|
|
name = str(data.get("name") or config.name or "").strip()
|
|
version = str(data.get("version") or config.version or "").strip()
|
|
if training_type not in TRAINING_TYPES:
|
|
raise ValidationError("training_type is invalid", details={"field": "training_type", "allowed": sorted(TRAINING_TYPES)})
|
|
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 = data["settings"]
|
|
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]:
|
|
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"})
|
|
config.resources = [TrainingConfigResource(**_validate_resource(item)) for item in data["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:
|
|
normalized_type = TRAINING_TYPE_ALIASES.get(str(training_type or "").strip(), str(training_type or "").strip().lower())
|
|
if normalized_type not in TRAINING_TYPES:
|
|
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')
|
|
],
|
|
}
|