254 lines
13 KiB
Python
254 lines
13 KiB
Python
"""
|
||
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 个"未被任何任务推送过"的视频(跨任务
|
||
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
|
||
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
|
||
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护),
|
||
再对各任务推进一批推送。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
|
||
from sqlalchemy import select
|
||
|
||
from app.extensions import db
|
||
from app.models import LeanTrainingVideoPushLog, LeanTrainingWeeklyTask, User
|
||
from app.services.lean_training_reminder_service import (
|
||
_send_reminder,
|
||
notify_overdue_users_after_push,
|
||
send_initial_target_notifications,
|
||
)
|
||
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"
|
||
|
||
|
||
def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeeklyTask | None:
|
||
"""
|
||
每周自动滚动:当周任务不存在时,以最近一期已发布任务为模板自动创建当周任务(无需人工维护)。
|
||
|
||
Args:
|
||
now: 覆盖当前时间(UTC naive,测试用)。
|
||
Returns:
|
||
当周任务(已存在或新建);系统内尚无任何历史任务模板时返回 None,等待管理员手动发布。
|
||
业务约束:
|
||
- 任务周=当周周一、截止时间=当周周日 23:59:59(服务端计算,每周自动更新);
|
||
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
|
||
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
|
||
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
|
||
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完;
|
||
- 配置中新增上传、尚未冻结进模板列表的视频按上传时间倒序自动追加到列表末尾:
|
||
HR 事后手动勾选补推的进度经游标继承持续生效,每周自动计划从断点继续向后推;
|
||
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推。
|
||
"""
|
||
week_start, due_at = _current_week_bounds(now)
|
||
week_key = week_start.isoformat()
|
||
existing = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.week_key == week_key)).scalar_one_or_none()
|
||
if existing:
|
||
return existing
|
||
template = db.session.execute(
|
||
select(LeanTrainingWeeklyTask)
|
||
.where(LeanTrainingWeeklyTask.status == "published", LeanTrainingWeeklyTask.week_key < week_key)
|
||
.order_by(LeanTrainingWeeklyTask.week_key.desc())
|
||
).scalars().first()
|
||
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=min(template.pushed_video_count, len(video_resource_ids)),
|
||
due_at=due_at,
|
||
video_resource_ids=video_resource_ids,
|
||
target_roles=list(template.target_roles or []),
|
||
target_user_ids=list(template.target_user_ids or []),
|
||
status="published",
|
||
)
|
||
db.session.add(task)
|
||
db.session.commit()
|
||
# [STEP 2] 同步发送任务发布通知(幂等),受训员工发布后立即可学
|
||
send_initial_target_notifications(task.id, now=now)
|
||
return task
|
||
|
||
|
||
def pending_video_ids(task: LeanTrainingWeeklyTask) -> list[int]:
|
||
"""返回当前任务尚未推送的视频 ID 列表(保持选择顺序,供游标推进与耗尽判断使用)。"""
|
||
return list(task.video_resource_ids or [])[task.pushed_video_count:]
|
||
|
||
|
||
def serialize_push_log(log: LeanTrainingVideoPushLog) -> dict[str, object]:
|
||
"""序列化推送日志,供管理端展示每轮推送的批次、数量与失败原因。"""
|
||
return {
|
||
"id": log.id,
|
||
"weekly_task_id": log.weekly_task_id,
|
||
"trigger": log.trigger,
|
||
"pushed_resource_ids": list(log.pushed_resource_ids or []),
|
||
"pushed_count": log.pushed_count,
|
||
"recipient_count": log.recipient_count,
|
||
"sent_count": log.sent_count,
|
||
"skipped_count": log.skipped_count,
|
||
"failed_count": log.failed_count,
|
||
"status": log.status,
|
||
"error_message": log.error_message,
|
||
"created_by_id": log.created_by_id,
|
||
"created_at": log.created_at.isoformat() if log.created_at else None,
|
||
}
|
||
|
||
|
||
def list_push_logs(task_id: int, *, limit: int = 50) -> list[dict[str, object]]:
|
||
"""按时间倒序返回指定周任务的推送日志,供管理端"推送记录"区块展示。"""
|
||
logs = db.session.execute(
|
||
select(LeanTrainingVideoPushLog)
|
||
.where(LeanTrainingVideoPushLog.weekly_task_id == task_id)
|
||
.order_by(LeanTrainingVideoPushLog.id.desc())
|
||
.limit(limit)
|
||
).scalars().all()
|
||
return [serialize_push_log(log) for log in logs]
|
||
|
||
|
||
def push_lean_training_videos(
|
||
task_id: int,
|
||
*,
|
||
trigger: str = "schedule",
|
||
current_user_id: int | None = None,
|
||
now: datetime | None = None,
|
||
) -> dict[str, object]:
|
||
"""
|
||
推送下一批精益培训视频(数量=weekly_count)并写推送日志。
|
||
|
||
Args:
|
||
task_id: 精益周任务 ID,必须为已发布状态。
|
||
trigger: 推送来源,publish=发布任务立即推首批 / schedule=每周一排程 / manual=管理端手动推送。
|
||
current_user_id: 手动推送时的操作人,写入日志审计。
|
||
now: 覆盖当前时间(测试用)。
|
||
|
||
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 个"未被任何任务推送过"的新视频;
|
||
# 已被其它任务推送过的视频仅越过(游标同步越过),绝不重复进入批次;无新视频可推时不发企微
|
||
candidates = pending_video_ids(task)
|
||
if not candidates:
|
||
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
|
||
start_index = task.pushed_video_count
|
||
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")
|
||
).scalars().all()
|
||
counts = {"sent": 0, "skipped": 0, "failed": 0}
|
||
failure_details: list[str] = []
|
||
for recipient in recipients:
|
||
result = _send_reminder(
|
||
task=task,
|
||
recipient=recipient,
|
||
event_key=event_key,
|
||
event_type=VIDEO_PUSH_EVENT_TYPE,
|
||
title="精益管理培训视频推送",
|
||
content=f"本周精益管理培训已更新,请观看 {len(batch)} 个新视频并提交不少于50字的学习感悟。",
|
||
current=current,
|
||
)
|
||
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 + 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,
|
||
trigger=trigger,
|
||
pushed_resource_ids=batch,
|
||
pushed_count=len(batch),
|
||
recipient_count=len(recipients),
|
||
sent_count=counts["sent"],
|
||
skipped_count=counts["skipped"],
|
||
failed_count=counts["failed"],
|
||
status=status,
|
||
error_message=";".join(failure_details)[:2000] if failure_details else None,
|
||
created_by_id=current_user_id,
|
||
)
|
||
db.session.add(log)
|
||
db.session.commit()
|
||
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
|
||
notify_overdue_users_after_push(
|
||
task,
|
||
event_key=f"overdue-after-push-{start_index}-{start_index + len(batch)}",
|
||
current=current,
|
||
)
|
||
return serialize_push_log(log)
|
||
|
||
|
||
def run_lean_training_video_push(*, now: datetime | None = None) -> dict[str, object]:
|
||
"""
|
||
排程入口(每周一 09:00):先自动滚动创建当周任务(无需人工维护),再对当周任务推进一批视频推送。
|
||
|
||
业务约束:
|
||
- 仅推进当周任务,保证"视频列表顺序分批、跨周连续、不重复推"的单一进度线;
|
||
- 历史任务不再由排程推进,其补推由管理端手动触发(立即新增任务补推);
|
||
- 系统内尚无任务模板时无事可做,返回 completed 汇总。
|
||
"""
|
||
current = now or utc_now_naive()
|
||
week_task = ensure_current_week_task(now=current)
|
||
if week_task is None:
|
||
return {"tasks": 0, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
|
||
result = push_lean_training_videos(week_task.id, trigger="schedule", now=current)
|
||
if result.get("status") == "completed":
|
||
return {"tasks": 1, "pushed": 0, "sent": 0, "skipped": 0, "failed": 0, "completed": 1, "task_results": []}
|
||
return {
|
||
"tasks": 1,
|
||
"pushed": int(result.get("pushed_count") or 0),
|
||
"sent": int(result.get("sent_count") or 0),
|
||
"skipped": int(result.get("skipped_count") or 0),
|
||
"failed": int(result.get("failed_count") or 0),
|
||
"completed": 0,
|
||
"task_results": [result],
|
||
}
|