""" backend/app/services/lean_training_service.py 用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。 依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。 逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;员工仅对已推送批次提交观看事实与学习感悟; 服务端按 50 字门槛判定完成,管理看板只读取已授权范围。 """ from __future__ import annotations from datetime import date, datetime, time, timedelta, timezone from typing import Any from sqlalchemy import func, 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.minio_service import minio_service 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 _current_week_bounds(now: datetime | None = None) -> tuple[date, datetime]: """ 计算当周任务边界(Asia/Shanghai):任务周=当周周一,截止时间=当周周日 23:59:59。 Args: now: 覆盖当前时间(UTC naive,测试用);缺省取当前 UTC 时间。 Returns: (week_start, due_at_utc):week_start 为周一日期(ISO week_key),due_at_utc 为转 UTC 后的 naive 截止时间。 业务约束:任务周与截止时间由服务端强制计算,客户端只读不可修改,每周自动滚动更新。 """ shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai") current = now or utc_now_naive() local_now = current.replace(tzinfo=timezone.utc).astimezone(shanghai_tz) week_start = local_now.date() - timedelta(days=local_now.weekday()) due_local = datetime.combine(week_start + timedelta(days=6), time(23, 59, 59), tzinfo=shanghai_tz) return week_start, to_utc_naive(due_local) def week_index_for_task(task: LeanTrainingWeeklyTask) -> int: """返回任务期号:按 week_key 升序编号,最早一周为第 1 期(供前端展示"第N周")。""" earlier_count = db.session.execute( select(func.count(LeanTrainingWeeklyTask.id)).where(LeanTrainingWeeklyTask.week_key < task.week_key) ).scalar() or 0 return int(earlier_count) + 1 def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]: """ 校验周任务绑定的视频资源并返回冻结顺序列表。 Args: value: 管理端提交的 video_resource_ids;为 None/空列表时按新规则自动填充。 config: 已发布的精益培训配置,仅其下视频类型资源可选。 Returns: 去重后的视频资源 ID 顺序列表(即每周分批推送顺序)。 业务约束: - 显式选择时按选择顺序冻结(每周按此顺序分批推送); - 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则); - 推过的视频不能重复推:由推送游标(pushed_video_count)保证,直至全部视频推完。 """ video_resources = [ 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") ] # [RULE] 管理端未显式勾选视频时,按上传时间倒序自动冻结全部视频,满足"直至全部上传视频推送完" if not isinstance(value, list) or len(value) == 0: if value is not None and not isinstance(value, list): raise ValidationError("video_resource_ids must be a list", details={"field": "video_resource_ids"}) ordered = sorted(video_resources, key=lambda resource: resource.created_at or datetime.min, reverse=True) if not ordered: raise ValidationError("At least one lean training video is required", details={"field": "video_resource_ids"}) return [resource.id for resource in ordered] if len({str(item) for item in value}) != len(value): raise ValidationError("video_resource_ids contains duplicate items", details={"field": "video_resource_ids"}) resource_map = {resource.id: resource for resource in video_resources} 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, *, learner_view: bool = False) -> dict[str, Any]: """序列化精益周任务;员工端视图仅含已推送视频前缀(游标内),管理端返回全量选择列表。 videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。 附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。 """ visible_ids = list(task.video_resource_ids or []) if learner_view: visible_ids = visible_ids[: task.pushed_video_count] resources = db.session.execute( select(TrainingConfigResource).where(TrainingConfigResource.id.in_(visible_ids)) ).scalars().all() titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in resources} file_urls = { resource.id: (minio_service.get_public_url(resource.agent_guide.file_path) if resource.agent_guide and resource.agent_guide.file_path else "") for resource in resources } try: week_start = date.fromisoformat(task.week_key) except ValueError: week_start = None return { "id": task.id, "week_key": task.week_key, "week_end": (week_start + timedelta(days=6)).isoformat() if week_start else None, "week_index": week_index_for_task(task), "due_at": task.due_at.isoformat(), "video_resource_ids": visible_ids, "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, ""), "file_url": file_urls.get(resource_id, "")} for resource_id in visible_ids], "status": task.status, "min_summary_length": MIN_SUMMARY_LENGTH, "weekly_count": task.weekly_count, "pushed_video_count": task.pushed_video_count, } def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]: """ 创建或更新精益视频周任务,并由 HR 冻结视频列表、每周推送数量与受训对象。 业务约束(周任务规则): - 任务周支持修改:显式传 week_key(必须为该周周一)即按所选自然周创建/更新,缺省回落当周周一; - 截止时间支持修改:显式传 due_at 按所选时刻落库,缺省为所选周周日 23:59:59; 不得早于所选周周一 00:00(Asia/Shanghai),避免任务创建即处于"已延期"的明显配置错误; - 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批); - 同周重复提交为更新(游标不回退),新周提交为新建。 """ config = _get_lean_config() shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai") # [STEP 1] 任务周与截止时间:优先取表单显式指定(支持修改为任意自然周),未指定时回落当周(周一 ~ 周日 23:59:59) week_start, due_at = _current_week_bounds() explicit_week_key = str(data.get("week_key") or "").strip() if explicit_week_key: try: week_start = date.fromisoformat(explicit_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"}) explicit_due_at = str(data.get("due_at") or "").strip() if explicit_due_at: try: due_at = to_utc_naive(datetime.fromisoformat(explicit_due_at.replace("Z", "+00:00"))) except ValueError as exc: raise ValidationError("due_at is invalid", details={"field": "due_at"}) from exc else: due_at = to_utc_naive(datetime.combine(week_start + timedelta(days=6), time(23, 59, 59), tzinfo=shanghai_tz)) # 截止时间下限校验:早于所选周周一 00:00 意味着任务一经创建即整周过期,视为配置错误 week_floor = to_utc_naive(datetime.combine(week_start, time(0, 0, 0), tzinfo=shanghai_tz)) if due_at < week_floor: raise ValidationError("due_at must not be earlier than the Monday of the selected week", details={"field": "due_at"}) existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_start.isoformat())).scalar_one_or_none() video_ids = _normalize_video_ids(data.get("video_resource_ids"), config) 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"}) weekly_count = data.get("weekly_count", 1) try: weekly_count = int(weekly_count) except (TypeError, ValueError) as exc: raise ValidationError("weekly_count must be a positive integer", details={"field": "weekly_count"}) from exc if weekly_count < 1 or weekly_count > 50: raise ValidationError("weekly_count must be between 1 and 50", details={"field": "weekly_count"}) # 新实例必须显式给游标初值:列 default 仅在 INSERT 时生效,Python 侧构造后为 None,直接参与 min() 会抛 TypeError task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_start.isoformat(), created_by_id=user_id, weekly_count=1, pushed_video_count=0) task.due_at = due_at task.video_resource_ids = video_ids # [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推 task.pushed_video_count = min(task.pushed_video_count, len(video_ids)) task.weekly_count = weekly_count 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_weekly_task_for_admin(task_id: int) -> dict[str, Any] | None: """按 ID 返回管理端视图的周任务(全量视频列表),任务不存在时返回 None。""" task = db.session.get(LeanTrainingWeeklyTask, task_id) return serialize_weekly_task(task) if task else None 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, learner_view=True) if task else None def list_my_weekly_tasks(user: User) -> list[dict[str, Any]]: """ 返回当前员工被指派的全部已发布精益周任务(按周期倒序,最新在最上),供员工端时间树展示。 每项为学员视角序列化(仅已推送视频前缀),并附加: - task_status: completed=已完成感悟提交(completed_at 非空);overdue=未完成且已过截止时间;in_progress=未完成且未到截止; - completion: 观看草稿(仅记录了视频观看、感悟未提交)或完成记录的总结/观看时间/完成时间摘要,两者均无时为 None。 """ tasks = db.session.execute( select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published").order_by(LeanTrainingWeeklyTask.week_key.desc()) ).scalars().all() targeted = [item for item in tasks if is_task_targeted_to_user(item, user)] if not targeted: return [] completions = { item.weekly_task_id: item for item in db.session.execute( select(LeanTrainingCompletion).where( LeanTrainingCompletion.user_id == user.id, LeanTrainingCompletion.weekly_task_id.in_([task.id for task in targeted]), ) ).scalars().all() } now = utc_now_naive() items: list[dict[str, Any]] = [] for task in targeted: completion = completions.get(task.id) item = serialize_weekly_task(task, learner_view=True) # 只有感悟提交完成(completed_at 非空)才算"已完成";仅有观看草稿时仍按截止时间判定进行中/已延期 item["task_status"] = "completed" if completion and completion.completed_at else ("overdue" if now > task.due_at else "in_progress") item["completion"] = { "summary_text": completion.summary_text, "watched_at": dict(completion.watched_at_json or {}), "completed_at": completion.completed_at.isoformat() if completion.completed_at else None, } if completion else None items.append(item) return items def mark_video_watched(user: User, data: dict[str, Any]) -> dict[str, Any]: """ 学员端持久化"单个任务视频已完成观看"记录:视频播放到结尾即保存,无需等待感悟提交。 Args: user: 当前登录员工。 data: 需包含 weekly_task_id 与 resource_id;resource_id 必须属于该任务已推送的前缀视频。 Returns: {"watched_at": {resource_id: 观看时间iso字符串}},该任务当前的全部观看记录。 Raises: NotFoundError: 任务不存在、未发布、未指派给该员工或视频不在已推送范围。 """ task_id = int(data.get("weekly_task_id") or 0) resource_id = int(data.get("resource_id") or 0) task = db.session.get(LeanTrainingWeeklyTask, task_id) if not task or task.status != "published" or not is_task_targeted_to_user(task, user): raise NotFoundError("Lean training weekly task not found") # 员工只能记录已推送前缀视频的观看,防止越权观看未发布视频 if resource_id not in list(task.video_resource_ids or [])[: task.pushed_video_count]: raise NotFoundError("Video resource not in pushed scope") 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) watched = dict(completion.watched_at_json or {}) if not watched.get(str(resource_id)): watched[str(resource_id)] = utc_now_naive().isoformat() completion.watched_at_json = watched # 观看草稿:保持 completed_at 为空,任务仍为进行中/已延期,直至感悟提交完成 db.session.add(completion) db.session.commit() return {"watched_at": watched} 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") # 员工只能观看已推送的前缀视频,完成校验同样基于已推送范围而非全量选择列表 required_ids = list(task.video_resource_ids or [])[: task.pushed_video_count] # 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看 watched = {str(key): str(value) for key, value in (data.get("watched_at") or {}).items()} 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) watched.update({str(key): str(value) for key, value in (completion.watched_at_json or {}).items()}) if not required_ids or not all(str(resource_id) in watched and watched[str(resource_id)] for resource_id in required_ids): raise ValidationError("All pushed 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.watched_at_json = watched 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 _task_video_rows(task: LeanTrainingWeeklyTask, completion: LeanTrainingCompletion | None) -> list[dict[str, Any]]: """ 生成看板行的视频明细:仅展示本周期内已推送、要求员工学习的视频(推送游标前缀),与学员端可见范围一致。 Args: task: 当前周任务,视频顺序按管理端冻结时的选择顺序展示(截断到推送游标)。 completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。 Returns: [{"name": 视频名, "watched_at": 观看时间iso或None}];尚未推送任何视频(游标为 0)时返回空列表,前端展示 "--"。 """ titles = {resource.id: resource.title or (resource.agent_guide.file_name if resource.agent_guide else "") for resource in task.config.resources} watched = dict(completion.watched_at_json or {}) if completion else {} # [RULE] 看板视频列只展示已推送前缀(video_resource_ids[:pushed_video_count]):未推送视频不属于本周期学习范围,避免名单出现从未布置过的视频 visible_ids = task.video_resource_ids[: task.pushed_video_count] return [ {"name": titles.get(resource_id, ""), "watched_at": watched.get(str(resource_id))} for resource_id in visible_ids ] def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User) -> dict[str, Any]: """组合看板所需人员、视频观看、总结和完成状态字段。""" # 状态三态归一:已提交感悟为 completed;未完成时按截止时间区分进行中/已延期,管理端状态列直接展示中文 if completion.status == "completed": status = "completed" else: status = "overdue" if utc_now_naive() > task.due_at else (completion.status or "in_progress") return { "id": completion.id, "user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, completion), "summary_text": completion.summary_text, "status": status, "completed_at": completion.completed_at.isoformat() if completion.completed_at else None, } def list_dashboard(task_id: int | None) -> dict[str, Any]: """返回 HR 可查看的精益看板,仅统计当前周任务已冻结的受训对象。 Args: task_id: 指定期次任务 ID;为空时返回最新一期。periods 字段返回全部期次摘要, 供管理端下拉区分/切换第几期任务(期号按周次升序,最早为第 1 期)。 """ all_tasks = db.session.execute(select(LeanTrainingWeeklyTask).order_by(LeanTrainingWeeklyTask.week_key.desc())).scalars().all() # [STEP 1] 期次摘要列表:无论是否指定期次都返回,期号按周次升序编号(最早的为第 1 期)。 periods = [{"id": t.id, "week_key": t.week_key, "index": i + 1} for i, t in enumerate(reversed(all_tasks))] task = db.session.get(LeanTrainingWeeklyTask, task_id) if task_id else (all_tasks[0] if all_tasks else None) if not task: return {"task": None, "completed": [], "incomplete": [], "periods": periods} 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": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None} (completed if row["status"] == "completed" else incomplete).append(row) return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}