""" 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 _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(服务端计算,每周自动更新); - 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周, 必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度; - 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度, 保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。 """ 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] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送) 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, due_at=due_at, video_resource_ids=list(template.video_resource_ids or []), 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。 业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。 """ 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: 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)}" # [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 + len(batch) 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], }