238 lines
13 KiB
Python
238 lines
13 KiB
Python
"""
|
|
backend/app/services/lean_training_service.py
|
|
|
|
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
|
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
|
逻辑:管理端冻结每周两个视频;员工提交观看事实与学习感悟;服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, datetime, time
|
|
from typing import Any
|
|
|
|
from sqlalchemy import or_, select
|
|
|
|
from app.core.errors import NotFoundError, ValidationError
|
|
from app.extensions import db
|
|
from app.models import (
|
|
LeanTrainingCompletion,
|
|
LeanTrainingWeeklyTask,
|
|
TrainingConfig,
|
|
TrainingConfigResource,
|
|
User,
|
|
)
|
|
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
|
|
|
LEAN_TRAINING_TYPE = "lean_management"
|
|
MIN_SUMMARY_LENGTH = 50
|
|
|
|
|
|
def _get_lean_config() -> TrainingConfig:
|
|
"""读取已发布精益培训配置,未配置时阻止创建周任务。"""
|
|
config = db.session.execute(
|
|
select(TrainingConfig).where(
|
|
TrainingConfig.training_type == LEAN_TRAINING_TYPE,
|
|
TrainingConfig.status == "published",
|
|
).order_by(TrainingConfig.id.desc())
|
|
).scalars().first()
|
|
if not config:
|
|
raise ValidationError("Lean training published config is required")
|
|
return config
|
|
|
|
|
|
def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
|
|
"""校验周任务必须绑定当前精益配置下恰好两个视频资源。"""
|
|
if not isinstance(value, list) or len(value) != 2 or len({str(item) for item in value}) != 2:
|
|
raise ValidationError("Exactly two lean training videos are required", details={"field": "video_resource_ids"})
|
|
resource_map = {
|
|
resource.id: resource
|
|
for resource in config.resources
|
|
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
|
|
}
|
|
ids: list[int] = []
|
|
for item in value:
|
|
try:
|
|
resource_id = int(item)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ValidationError("video_resource_ids contains invalid resource", details={"field": "video_resource_ids"}) from exc
|
|
if resource_id not in resource_map:
|
|
raise ValidationError("Selected resource is not a lean training video")
|
|
ids.append(resource_id)
|
|
return ids
|
|
|
|
|
|
def _normalize_target_roles(value: Any) -> list[str]:
|
|
"""校验 HR 按角色指定的精益周任务对象,角色值必须为非空且去重的系统角色。"""
|
|
if value is None:
|
|
return []
|
|
if not isinstance(value, list):
|
|
raise ValidationError("target_roles must be a list", details={"field": "target_roles"})
|
|
roles = sorted({str(item).strip() for item in value if str(item).strip()})
|
|
if len(roles) != len({str(item).strip() for item in value}):
|
|
raise ValidationError("target_roles contains invalid role", details={"field": "target_roles"})
|
|
return roles
|
|
|
|
|
|
def _normalize_target_user_ids(value: Any) -> list[int]:
|
|
"""校验 HR 指定的精益周任务对象,所有用户必须为在职系统用户。"""
|
|
if value is None:
|
|
return []
|
|
if not isinstance(value, list):
|
|
raise ValidationError("target_user_ids must be a list", details={"field": "target_user_ids"})
|
|
try:
|
|
user_ids = sorted({int(item) for item in value})
|
|
except (TypeError, ValueError) as exc:
|
|
raise ValidationError("target_user_ids contains invalid user", details={"field": "target_user_ids"}) from exc
|
|
if any(user_id <= 0 for user_id in user_ids):
|
|
raise ValidationError("target_user_ids contains invalid user", details={"field": "target_user_ids"})
|
|
found_ids = set(db.session.execute(select(User.id).where(User.id.in_(user_ids), User.status == "active")).scalars()) if user_ids else set()
|
|
if found_ids != set(user_ids):
|
|
raise ValidationError("target_user_ids contains unavailable user", details={"field": "target_user_ids"})
|
|
return user_ids
|
|
|
|
|
|
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
|
"""返回周任务的在职受训对象,角色和用户指定对象按并集处理。"""
|
|
predicates = []
|
|
if task.target_user_ids:
|
|
predicates.append(User.id.in_(list(task.target_user_ids)))
|
|
if task.target_roles:
|
|
predicates.append(User.role.in_(list(task.target_roles)))
|
|
if not predicates:
|
|
return set()
|
|
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
|
|
|
|
|
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
|
"""判断员工是否属于周任务对象,角色匹配或显式指定任一成立即可学习。"""
|
|
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
|
|
|
|
|
def serialize_weekly_task(task: LeanTrainingWeeklyTask) -> dict[str, Any]:
|
|
"""序列化精益周任务,返回视频标题和完成规则供管理端与员工端使用。"""
|
|
resources = db.session.execute(
|
|
select(TrainingConfigResource).where(TrainingConfigResource.id.in_(task.video_resource_ids or []))
|
|
).scalars().all()
|
|
titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in resources}
|
|
return {
|
|
"id": task.id,
|
|
"week_key": task.week_key,
|
|
"due_at": task.due_at.isoformat(),
|
|
"video_resource_ids": list(task.video_resource_ids or []),
|
|
"target_roles": list(task.target_roles or []),
|
|
"target_user_ids": list(task.target_user_ids or []),
|
|
"videos": [{"id": resource_id, "name": titles.get(resource_id, "")} for resource_id in task.video_resource_ids or []],
|
|
"status": task.status,
|
|
"min_summary_length": MIN_SUMMARY_LENGTH,
|
|
}
|
|
|
|
|
|
def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]:
|
|
"""创建或更新指定周的两个视频任务,并由 HR 按角色或用户冻结受训对象。"""
|
|
config = _get_lean_config()
|
|
week_key = str(data.get("week_key") or "").strip()
|
|
try:
|
|
week_start = date.fromisoformat(week_key)
|
|
except ValueError as exc:
|
|
raise ValidationError("week_key must be YYYY-MM-DD", details={"field": "week_key"}) from exc
|
|
if week_start.weekday() != 0:
|
|
raise ValidationError("week_key must be the Monday of its week", details={"field": "week_key"})
|
|
try:
|
|
due_at = to_utc_naive(datetime.fromisoformat(str(data.get("due_at") or "").replace("Z", "+00:00")))
|
|
except ValueError as exc:
|
|
raise ValidationError("due_at is invalid", details={"field": "due_at"}) from exc
|
|
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
|
|
minimum_due_at = to_utc_naive(datetime.combine(week_start, time.min, shanghai_tz))
|
|
if due_at < minimum_due_at:
|
|
raise ValidationError("due_at must not precede week_key", details={"field": "due_at"})
|
|
if due_at < utc_now_naive() and not bool(data.get("allow_historical")):
|
|
raise ValidationError("due_at must be in the future", details={"field": "due_at"})
|
|
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_key)).scalar_one_or_none()
|
|
video_ids = _normalize_video_ids(data.get("video_resource_ids"), config) if not existing else list(existing.video_resource_ids or [])
|
|
target_roles = _normalize_target_roles(data.get("target_roles"))
|
|
target_user_ids = _normalize_target_user_ids(data.get("target_user_ids"))
|
|
if not target_roles and not target_user_ids:
|
|
raise ValidationError("At least one target role or user is required", details={"field": "target_roles"})
|
|
task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_key, created_by_id=user_id)
|
|
task.due_at = due_at
|
|
task.video_resource_ids = video_ids
|
|
task.target_roles = target_roles
|
|
task.target_user_ids = target_user_ids
|
|
task.status = "published"
|
|
db.session.add(task)
|
|
db.session.commit()
|
|
return serialize_weekly_task(task)
|
|
|
|
|
|
def get_current_weekly_task(user: User) -> dict[str, Any] | None:
|
|
"""返回当前员工被指定的最新已发布周任务,未被指定时不暴露任务内容。"""
|
|
tasks = db.session.execute(
|
|
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published").order_by(LeanTrainingWeeklyTask.week_key.desc())
|
|
).scalars().all()
|
|
task = next((item for item in tasks if is_task_targeted_to_user(item, user)), None)
|
|
return serialize_weekly_task(task) if task else None
|
|
|
|
|
|
def save_completion(user: User, data: dict[str, Any]) -> dict[str, Any]:
|
|
"""保存员工精益学习事实并强制校验两项观看与不少于 50 字总结。"""
|
|
task_id = int(data.get("weekly_task_id") or 0)
|
|
task = db.session.get(LeanTrainingWeeklyTask, task_id)
|
|
if not task or task.status != "published":
|
|
raise NotFoundError("Lean training weekly task not found")
|
|
if not is_task_targeted_to_user(task, user):
|
|
raise NotFoundError("Lean training weekly task not found")
|
|
watched = data.get("watched_at")
|
|
if not isinstance(watched, dict) or not all(str(resource_id) in watched and watched[str(resource_id)] for resource_id in task.video_resource_ids):
|
|
raise ValidationError("Both required videos must be watched", details={"field": "watched_at"})
|
|
summary = str(data.get("summary_text") or "").strip()
|
|
char_count = len(summary)
|
|
if char_count < MIN_SUMMARY_LENGTH:
|
|
raise ValidationError("Learning summary must contain at least 50 characters", details={"field": "summary_text", "min_length": MIN_SUMMARY_LENGTH, "actual_length": char_count})
|
|
completion = db.session.execute(
|
|
select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.user_id == user.id)
|
|
).scalar_one_or_none() or LeanTrainingCompletion(weekly_task_id=task.id, user_id=user.id)
|
|
completion.watched_at_json = {str(key): str(value) for key, value in watched.items()}
|
|
completion.summary_text = summary
|
|
completion.summary_char_count = char_count
|
|
completion.status = "completed"
|
|
completion.completed_at = completion.completed_at or utc_now_naive()
|
|
db.session.add(completion)
|
|
db.session.commit()
|
|
return serialize_completion(completion, task, user)
|
|
|
|
|
|
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]:
|
|
"""组合看板所需人员、视频观看、总结和完成状态字段。"""
|
|
return {
|
|
"id": completion.id,
|
|
"user_id": user.id,
|
|
"employee_id": user.employee_id,
|
|
"name": user.real_name or user.username,
|
|
"department": user.department,
|
|
"videos": [
|
|
{"name": next((resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources if resource.id == resource_id), ""), "watched_at": (completion.watched_at_json or {}).get(str(resource_id))}
|
|
for resource_id in task.video_resource_ids
|
|
],
|
|
"summary_text": completion.summary_text,
|
|
"status": completion.status,
|
|
"completed_at": completion.completed_at.isoformat() if completion.completed_at else None,
|
|
}
|
|
|
|
|
|
def list_dashboard(task_id: int | None) -> dict[str, Any]:
|
|
"""返回 HR 可查看的精益看板,仅统计当前周任务已冻结的受训对象。"""
|
|
task = db.session.get(LeanTrainingWeeklyTask, task_id) if task_id else db.session.execute(select(LeanTrainingWeeklyTask).order_by(LeanTrainingWeeklyTask.week_key.desc())).scalars().first()
|
|
if not task:
|
|
return {"task": None, "completed": [], "incomplete": []}
|
|
target_user_ids = target_user_ids_for_task(task)
|
|
users = db.session.execute(select(User).where(User.id.in_(target_user_ids)).order_by(User.department, User.employee_id)).scalars().all() if target_user_ids else []
|
|
completions = {item.user_id: item for item in db.session.execute(select(LeanTrainingCompletion).where(LeanTrainingCompletion.weekly_task_id == task.id)).scalars().all()}
|
|
completed: list[dict[str, Any]] = []
|
|
incomplete: list[dict[str, Any]] = []
|
|
for user in users:
|
|
item = completions.get(user.id)
|
|
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": [], "summary_text": None, "status": "incomplete", "completed_at": None}
|
|
(completed if row["status"] == "completed" else incomplete).append(row)
|
|
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete}
|