719 lines
39 KiB
Python
719 lines
39 KiB
Python
"""
|
||
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,
|
||
PermissionRole,
|
||
TrainingConfig,
|
||
TrainingConfigResource,
|
||
User,
|
||
)
|
||
from app.models.permission_role import user_permission_roles
|
||
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 format_beijing_iso(value: datetime | str | None) -> str | None:
|
||
"""
|
||
将存储的 UTC 时间转换为北京时间 ISO 字符串,供页面/Excel 展示。
|
||
|
||
用途:培训模块数据库统一存 UTC naive(观看/完成/截止时间),而业务要求所有对外展示为北京时间;
|
||
此前序列化直接输出 UTC 导致页面显示比实际早 8 小时(如 18:47 显示 10:47)。
|
||
Args:
|
||
value: UTC naive datetime 或 ISO 字符串;naive 按 UTC 处理,带时区则先归一到绝对时间;
|
||
字符串无法解析时原样返回,避免历史脏数据导致展示层报错。
|
||
Returns:
|
||
带 +08:00 偏移的 ISO 字符串(如 2026-09-22T18:47:00+08:00,前端 slice(0,16) 即得北京时间);入参为空返回 None。
|
||
业务约束:仅用于序列化输出层,禁止将转换结果写回数据库——存储与服务端比较(超期判定等)仍一律 UTC。
|
||
"""
|
||
if value is None or (isinstance(value, str) and not value.strip()):
|
||
return None
|
||
if isinstance(value, str):
|
||
try:
|
||
parsed = datetime.fromisoformat(value.strip())
|
||
except ValueError:
|
||
return value.strip()
|
||
else:
|
||
parsed = value
|
||
if parsed.tzinfo is None:
|
||
parsed = parsed.replace(tzinfo=timezone.utc)
|
||
return parsed.astimezone(resolve_schedule_tzinfo("Asia/Shanghai")).isoformat()
|
||
|
||
|
||
def parse_client_iso_to_utc_text(text: str) -> str:
|
||
"""
|
||
将客户端回显的观看时间 ISO 字符串归一为 UTC naive ISO 文本,供存储。
|
||
|
||
用途:save_completion 会合并客户端提交的 watched_at 兜底值(服务端记录缺失时入库);
|
||
客户端时间格式随版本演进(UTC 带 Z / 北京时间带 +08:00),必须归一为 UTC,
|
||
否则 watched_at_json 混入非 UTC 值会破坏"存储一律 UTC"的约定,后续服务端比较将出错。
|
||
Args:
|
||
text: 客户端提交的 ISO 时间字符串。
|
||
Returns:
|
||
UTC naive ISO 文本;无法解析时原样返回(与历史行为一致,不因脏数据阻塞提交)。
|
||
"""
|
||
try:
|
||
parsed = datetime.fromisoformat(str(text))
|
||
except ValueError:
|
||
return str(text)
|
||
if parsed.tzinfo is None:
|
||
# naive 视为北京时间墙钟(新版客户端口径),入库前转 UTC
|
||
parsed = parsed.replace(tzinfo=resolve_schedule_tzinfo("Asia/Shanghai"))
|
||
return to_utc_naive(parsed).isoformat()
|
||
|
||
|
||
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:
|
||
role_codes = list(task.target_roles)
|
||
member_ids = (
|
||
select(user_permission_roles.c.user_id)
|
||
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||
.where(PermissionRole.code.in_(role_codes))
|
||
)
|
||
predicates.append(or_(User.role.in_(role_codes), User.id.in_(member_ids)))
|
||
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:
|
||
"""判断员工是否属于周任务对象。任一已挂角色命中,或显式指定用户,即可学习。"""
|
||
if user.status != "active":
|
||
return False
|
||
if user.id in set(task.target_user_ids or []):
|
||
return True
|
||
codes = set(task.target_roles or [])
|
||
if not codes:
|
||
return False
|
||
from app.services.permission_roles.service import list_assigned_roles, roles_configured
|
||
|
||
assigned = {str(user.role or "")}
|
||
if roles_configured():
|
||
assigned.update(role.code for role in list_assigned_roles(user))
|
||
return bool(assigned & codes)
|
||
|
||
|
||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||
"""
|
||
序列化精益周任务;管理端返回全量选择列表,学员端视图仅含本任务首次推送的视频(本期视频)。
|
||
|
||
videos 每项附带 file_url(MinIO 公开地址),供学员端视频缩略图与点击播放使用。
|
||
附带 week_index(第 N 期)与 week_end(周日),供前后端拼装"第N周 MM-DD至MM-DD"周次标签。
|
||
Args:
|
||
own_pushed_ids: 调用方已批量算好的本任务首推视频列表(如列表页一次归一遍历);
|
||
缺省时内部单任务计算,避免调用方重复查询。
|
||
"""
|
||
visible_ids = list(task.video_resource_ids or [])
|
||
if learner_view:
|
||
# [RULE] 学员端"本期视频"不含其它更早期任务已推送的视频:自动滚动复制上一期冻结列表时,
|
||
# 上一期已推送视频不再重复展示、也不要求重学(推过的视频不能重复再推)
|
||
visible_ids = own_pushed_ids if own_pushed_ids is not None else _own_pushed_video_ids(task)
|
||
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),
|
||
# 展示层转北京时间:管理端编辑器/看板头与学员端均直接渲染该字段,UTC 直出会比实际早 8 小时
|
||
"due_at": format_beijing_iso(task.due_at),
|
||
"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 _first_pushed_video_ids_map() -> dict[int, list[int]]:
|
||
"""
|
||
一次性计算全部已发布周任务的"本任务首次推送视频"归属映射。
|
||
|
||
用途:修复自动滚动把上一期冻结列表原样复制进新一期后,学员端按累积前缀(video_resource_ids[:pushed_video_count])
|
||
展示与考核,导致上一期已推送视频在第2期重复出现、并要求员工重看重写感悟的问题
|
||
(对应"前面任务中推送过的视频不能重复再推"规则,2026-09-29 方案 A)。
|
||
核心逻辑:按周次升序(同期唯一)遍历已发布任务,维护"此前已被推送过"的全局集合;
|
||
各任务已推送前缀中首次出现的视频归属本任务,与更早期任务重复的视频不属于本任务(本期无需重学)。
|
||
Returns:
|
||
{task_id: 本任务首次推送的视频资源 ID 顺序列表(保持冻结列表内的相对顺序)}。
|
||
"""
|
||
tasks = db.session.execute(
|
||
select(LeanTrainingWeeklyTask)
|
||
.where(LeanTrainingWeeklyTask.status == "published")
|
||
.order_by(LeanTrainingWeeklyTask.week_key, LeanTrainingWeeklyTask.id)
|
||
).scalars().all()
|
||
seen: set[int] = set()
|
||
ownership: dict[int, list[int]] = {}
|
||
for task in tasks:
|
||
prefix_ids = [int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count]]
|
||
ownership[task.id] = [resource_id for resource_id in prefix_ids if resource_id not in seen]
|
||
seen.update(prefix_ids)
|
||
return ownership
|
||
|
||
|
||
def _own_pushed_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
|
||
"""
|
||
返回指定任务的"本期视频":已推送前缀中本任务首次推送(此前其它任务未推送过)的部分。
|
||
|
||
用途:学员端展示、观看/完成校验、管理看板视频列统一按此口径取"本周期实际布置的视频",
|
||
保证自动滚动复制上一期列表后,上一期已推送视频不再重复出现在新一期。
|
||
Args:
|
||
task: 精益周任务。
|
||
Returns:
|
||
本任务首次推送的视频资源 ID 顺序列表。
|
||
"""
|
||
return _first_pushed_video_ids_map().get(task.id, [])
|
||
|
||
|
||
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 []
|
||
# [STEP] 一次遍历算出各任务首推视频归属,列表页逐任务序列化复用,避免 N 个任务各查一遍全表
|
||
own_pushed_map = _first_pushed_video_ids_map()
|
||
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, own_pushed_ids=own_pushed_map.get(task.id, []))
|
||
# 只有感悟提交完成(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,
|
||
# 展示层转北京时间:学员端"已观看"直接渲染该字典值,存储仍为 UTC
|
||
"watched_at": {key: format_beijing_iso(value) for key, value in (completion.watched_at_json or {}).items()},
|
||
"completed_at": format_beijing_iso(completion.completed_at),
|
||
} 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 _own_pushed_video_ids(task):
|
||
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()
|
||
# 返回值供学员端即时回显"已观看时间",展示层转北京时间;数据库中保持 UTC
|
||
return {"watched_at": {key: format_beijing_iso(value) for key, value in watched.items()}}
|
||
|
||
|
||
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 = _own_pushed_video_ids(task)
|
||
# 观看记录以服务端持久化为准(mark_video_watched 已逐个保存),客户端仅作回显兜底,防止伪造观看
|
||
# 兜底值入库前归一为 UTC:客户端可能提交北京时间(+08:00)或 UTC(Z)格式,存储一律 UTC
|
||
watched = {str(key): parse_client_iso_to_utc_text(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, own_video_ids: list[int] | None = None) -> list[dict[str, Any]]:
|
||
"""
|
||
生成看板行的视频明细:仅展示本周期内布置、要求员工学习的视频(本任务首次推送部分),与学员端可见范围一致。
|
||
|
||
Args:
|
||
task: 当前周任务,视频顺序按冻结列表内的相对顺序展示。
|
||
completion: 该员工的完成记录;从未观看(无完成记录)时传 None,仅返回视频名称清单(观看时间为 None)。
|
||
own_video_ids: 调用方已批量算好的本任务首推视频列表(看板逐行透传,避免每行重算);缺省时内部单任务计算。
|
||
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] 看板视频列只展示本期布置的视频(本任务首推部分):上一期已推送的视频不属于本周期学习范围,避免要求重学
|
||
visible_ids = own_video_ids if own_video_ids is not None else _own_pushed_video_ids(task)
|
||
return [
|
||
{"name": titles.get(resource_id, ""), "watched_at": format_beijing_iso(watched.get(str(resource_id)))}
|
||
for resource_id in visible_ids
|
||
]
|
||
|
||
|
||
def serialize_completion(completion: LeanTrainingCompletion, task: LeanTrainingWeeklyTask, user: User, own_video_ids: list[int] | None = None) -> dict[str, Any]:
|
||
"""组合看板所需人员、视频观看、总结和完成状态字段;own_video_ids 供看板批量透传本期视频口径。"""
|
||
# 状态三态归一:已提交感悟为 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, own_video_ids=own_video_ids),
|
||
"summary_text": completion.summary_text,
|
||
"status": status,
|
||
"completed_at": format_beijing_iso(completion.completed_at),
|
||
}
|
||
|
||
|
||
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()}
|
||
# [STEP] 本期视频口径一次算好逐行透传:看板按人逐行输出,避免每行重算首推归属
|
||
own_video_ids = _own_pushed_video_ids(task)
|
||
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, own_video_ids=own_video_ids) 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, own_video_ids=own_video_ids), "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
|