Files
syops/backend/app/services/lean_training_service.py
T

593 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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 io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import func, or_, select
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import (
Agent,
LeanTrainingCompletion,
LeanTrainingWeeklyTask,
TrainingConfig,
TrainingConfigResource,
User,
)
from app.services.integrations.minio 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
# 精益提醒/推送企微卡片跳转 Agent 的历史默认值;仅当动态解析失败(系统内无培训 Agent)时兜底
LEGACY_LEAN_JUMP_AGENT_ID = 27
def resolve_lean_training_jump_agent_id() -> int:
"""
解析精益提醒/推送企微卡片落地聊天页的「员工培训」Agent ID。
用途:卡片须跳 /chat/<培训agent>?training_type=lean_management,由前端 TrainingWorkspacePanel
自动展开精益页签;前端仅在目标 Agent 是培训 Agent 时才消费深链参数,
因此 Agent ID 指错环境会导致卡片落地后无法定位精益模块。
核心逻辑:各环境培训 Agent ID 不同,禁止依赖固定值——优先取 WECOM_LEAN_TRAINING_JUMP_AGENT_ID
显式配置覆盖,否则在启用 Agent 中按 handler_config.content_profile='training' 动态解析;
均不可用时回退历史默认 27 保持兼容。
Returns:
培训 Agent ID。
"""
from flask import current_app
override = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 0)
if override > 0:
return override
agents = db.session.execute(
select(Agent).where(Agent.is_active.is_(True)).order_by(Agent.sort_order, Agent.id)
).scalars().all()
for agent in agents:
handler_config = agent.handler_config if isinstance(agent.handler_config, dict) else {}
if str(handler_config.get("content_profile") or "").strip() == "training":
return int(agent.id)
return LEGACY_LEAN_JUMP_AGENT_ID
def _format_dashboard_datetime(value: str | None) -> str:
"""将看板 ISO 时间统一为页面展示的年月日时分格式。"""
text = str(value or "").strip()
return text[:16].replace("T", " ") if text else ""
def _dashboard_status_label(status: str | None) -> str:
"""将看板状态转换为页面一致的中文文案。"""
return {
"completed": "已完成",
"overdue": "已延期",
"in_progress": "进行中",
}.get(str(status or ""), str(status or ""))
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 _config_video_resource_ids(config: TrainingConfig) -> list[TrainingConfigResource]:
"""
返回精益配置下全部"视频型"学习资源(agent_guide 且文件类型为 video)。
用途:冻结列表自动填充与每周自动滚动追加新增视频共用同一判定,避免两处视频口径漂移。
Args:
config: 已发布的精益培训配置(需含 resources 关系)。
Returns:
视频资源列表(顺序由调用方排序)。
"""
return [
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")
]
def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
"""
校验周任务绑定的视频资源并返回冻结顺序列表。
Args:
value: 管理端提交的 video_resource_ids;为 None/空列表时按新规则自动填充。
config: 已发布的精益培训配置,仅其下视频类型资源可选。
Returns:
去重后的视频资源 ID 顺序列表(即每周分批推送顺序)。
业务约束:
- 显式选择时按选择顺序冻结(每周按此顺序分批推送);
- 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则);
- 推过的视频不能重复推:由推送游标(pushed_video_count)保证,直至全部视频推完。
"""
video_resources = _config_video_resource_ids(config)
# [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 _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[int]:
"""
汇总全部已发布周任务中"实际已推送过员工"的视频资源 ID(各任务推送前缀的并集)。
用途:作为跨任务去重基线,保证"推过的视频绝对不能重复推"——新建任务继承游标与推送分批都以此集合为准。
Args:
exclude_task_id: 需要排除的任务 ID(对已存在任务推进批次时排除自身,自身前缀已由游标表达)。
Returns:
已推送视频资源 ID 集合。
"""
tasks = db.session.execute(
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")
).scalars().all()
pushed: set[int] = set()
for task in tasks:
if exclude_task_id is not None and task.id == exclude_task_id:
continue
pushed.update(int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count])
return pushed
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
"""
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
用途:修复 HR 手动新建下一期任务时游标从 0 重推首批的问题——必须从上一任务断点续推。
核心逻辑:以已推送前缀并集为基线,从头统计新列表中有多少个视频已被推送过;
列表与上一期一致时精确继承断点;自动填充顺序因新上传视频变化时也能正确定位到首个未推送视频。
Args:
video_ids: 新任务冻结的视频资源 ID 顺序列表。
Returns:
继承后的推送游标(0 <= 游标 <= len(video_ids))。
"""
already_pushed = _already_pushed_resource_ids()
inherited = 0
for resource_id in video_ids:
if int(resource_id) not in already_pushed:
break
inherited += 1
return inherited
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),避免任务创建即处于"已延期"的明显配置错误;
- 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批);
- 同周重复提交为更新(游标不回退),新周提交为新建;
- 新建任务的推送游标从历史已推送进度继承(新列表的最长已推送前缀),推过的视频绝不从 0 重推,
后续批次自动从上一任务断点继续向后推进。
"""
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
if existing:
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
else:
# [RULE] 手动新建周任务继承历史推送进度:推过的视频绝不从 0 重推,从上一任务断点续推
task.pushed_video_count = _inherited_pushed_video_count(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}
def export_dashboard_excel(task_id: int | None) -> tuple[bytes, str]:
"""导出指定精益培训期次的完整看板数据。
Args:
task_id: 指定周任务 ID;为空时按看板规则导出最新一期。
Returns:
Excel 二进制内容与下载文件名;无可导出任务时抛出 NotFoundError。
"""
dashboard = list_dashboard(task_id)
task = dashboard["task"]
if not task:
raise NotFoundError("Lean training weekly task not found")
workbook = Workbook()
worksheet = workbook.active
worksheet.title = "lean_training"
worksheet.append(["期号", "培训周次", "截止时间", "工号", "姓名", "部门", "视频名称", "观看时间", "状态", "学习感悟", "完成时间"])
rows = [*dashboard["completed"], *dashboard["incomplete"]]
for row in rows:
videos = row.get("videos") or []
worksheet.append([
task.get("week_index") or "",
task.get("week_key") or "",
_format_dashboard_datetime(task.get("due_at")),
row.get("employee_id") or "",
row.get("name") or "",
row.get("department") or "",
"\n".join(str(video.get("name") or "") for video in videos),
"\n".join(_format_dashboard_datetime(video.get("watched_at")) for video in videos),
_dashboard_status_label(row.get("status")),
row.get("summary_text") or "",
_format_dashboard_datetime(row.get("completed_at")),
])
buffer = BytesIO()
workbook.save(buffer)
filename = f"lean_training_dashboard_{task['week_key']}.xlsx"
return buffer.getvalue(), filename