feat(lean-training): 手动新建周任务继承推送游标并自动滚动追加新增视频防重复推送

This commit is contained in:
runny committed 2026-09-18 10:29:30 +08:00
1 parent 89a033f0f9
commit f3cd5e7ae7
10 files changed
+228 -43

No files matched your search

@@ -4,9 +4,11 @@ backend/app/services/lean_training_push_service.py
用途:按"每周任务数量"分批推送精益培训视频给受训对象并发送企微通知,记录每轮推送日志;
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
逻辑:以 task.pushed_video_count 为游标,按视频冻结顺序每次取 weekly_count 个视频;员工端展示已推送前缀;
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置,无需人工维护),再对各任务推进一批推送。
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护),
再对各任务推进一批推送。
"""
from __future__ import annotations
@@ -22,7 +24,12 @@ from app.services.lean_training_reminder_service import (
notify_overdue_users_after_push,
send_initial_target_notifications,
)
from app.services.lean_training_service import _current_week_bounds, target_user_ids_for_task
from app.services.lean_training_service import (
_already_pushed_resource_ids,
_config_video_resource_ids,
_current_week_bounds,
target_user_ids_for_task,
)
from app.services.schedule.timezone_util import utc_now_naive
VIDEO_PUSH_EVENT_TYPE = "training_lean_video_push"
@@ -41,7 +48,10 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完;
- 配置中新增上传、尚未冻结进模板列表的视频按上传时间倒序自动追加到列表末尾:
HR 事后手动勾选补推的进度经游标继承持续生效,每周自动计划从断点继续向后推;
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推。
"""
week_start, due_at = _current_week_bounds(now)
week_key = week_start.isoformat()
@@ -56,14 +66,26 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
if not template:
return None
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
video_resource_ids = list(template.video_resource_ids or [])
# [RULE] 自动追加配置新增视频(上传时间倒序、只追加到末尾):前缀与游标保持对齐,断点续推不重推
frozen_ids = {int(resource_id) for resource_id in video_resource_ids}
video_resource_ids.extend(
resource.id
for resource in sorted(
_config_video_resource_ids(template.config),
key=lambda resource: resource.created_at or datetime.min,
reverse=True,
)
if resource.id not in frozen_ids
)
task = LeanTrainingWeeklyTask(
config_id=template.config_id,
week_key=week_key,
created_by_id=template.created_by_id,
weekly_count=template.weekly_count,
pushed_video_count=template.pushed_video_count,
pushed_video_count=min(template.pushed_video_count, len(video_resource_ids)),
due_at=due_at,
video_resource_ids=list(template.video_resource_ids or []),
video_resource_ids=video_resource_ids,
target_roles=list(template.target_roles or []),
target_user_ids=list(template.target_user_ids or []),
status="published",
@@ -128,18 +150,36 @@ def push_lean_training_videos(
Returns:
含 status(completed=无待推视频/partial/failed/sent)、batch、counts 与日志字段的 dict。
业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。
业务约束:
- 企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中;
- 跨任务绝对去重:已被其它周任务推送过的视频不进入本批(游标越过),待推区间全部重复时
游标直接推进到末尾并返回 completed,不发送企微。
"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
raise ValueError("Lean training weekly task not found")
current = now or utc_now_naive()
# [STEP 1] 计算本批视频:按选择顺序从游标起取 weekly_count 个;无待推视频时视为全部推送完
batch = pending_video_ids(task)[: task.weekly_count]
if not batch:
# [STEP 1] 计算本批视频:按选择顺序从游标向后扫描,取满 weekly_count 个"未被任何任务推送过"的新视频;
# 已被其它任务推送过的视频仅越过(游标同步越过),绝不重复进入批次;无新视频可推时不发企微
candidates = pending_video_ids(task)
if not candidates:
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
start_index = task.pushed_video_count
event_key = f"video-push-{start_index}-{start_index + len(batch)}"
already_pushed = _already_pushed_resource_ids(exclude_task_id=task.id)
batch: list[int] = []
consumed = 0
for resource_id in candidates:
if len(batch) >= task.weekly_count:
break
consumed += 1
if int(resource_id) not in already_pushed:
batch.append(resource_id)
if not batch:
# [RULE] 待推区间已全部被其它任务推送过:游标推进到末尾即视为全部推完,不重复推送、不重复打扰
task.pushed_video_count = start_index + consumed
db.session.commit()
return {"status": "completed", "message": "all pending videos already pushed", "pushed_count": 0}
event_key = f"video-push-{start_index}-{start_index + consumed}"
# [STEP 2] 面向全体在职受训对象发送企微通知;event_key 按批次区间幂等,同批重推不重复打扰
recipients = db.session.execute(
select(User).where(User.id.in_(target_user_ids_for_task(task)), User.status == "active")
@@ -159,8 +199,8 @@ def push_lean_training_videos(
counts[result] = counts.get(result, 0) + 1
if result == "failed" and recipient.id not in {line.split(":")[0] for line in failure_details}:
failure_details.append(f"{recipient.id}:{recipient.real_name or recipient.username}")
# [STEP 3] 游标前进(企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + len(batch)
# [STEP 3] 游标前进(越过跳过的重复视频与本批新视频;企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + consumed
status = "sent" if counts["failed"] == 0 else ("failed" if counts["sent"] == 0 and counts["skipped"] == 0 else "partial")
log = LeanTrainingVideoPushLog(
weekly_task_id=task.id,
+68 -7
View File
@@ -86,6 +86,22 @@ def week_index_for_task(task: LeanTrainingWeeklyTask) -> int:
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]:
"""
校验周任务绑定的视频资源并返回冻结顺序列表。
@@ -100,10 +116,7 @@ def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
- 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则);
- 推过的视频不能重复推:由推送游标(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")
]
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):
@@ -212,6 +225,48 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
}
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 冻结视频列表、每周推送数量与受训对象。
@@ -221,7 +276,9 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
- 截止时间支持修改:显式传 due_at 按所选时刻落库,缺省为所选周周日 23:59:59;
不得早于所选周周一 00:00(Asia/Shanghai),避免任务创建即处于"已延期"的明显配置错误;
- 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批);
- 同周重复提交为更新(游标不回退),新周提交为新建。
- 同周重复提交为更新(游标不回退),新周提交为新建;
- 新建任务的推送游标从历史已推送进度继承(新列表的最长已推送前缀),推过的视频绝不从 0 重推,
后续批次自动从上一任务断点继续向后推进。
"""
config = _get_lean_config()
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
@@ -264,8 +321,12 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
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))
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