fix(training): 精益催办按人按天合并去重,多期未完成仅发一条汇总提醒

This commit is contained in:
runny committed 2026-09-30 13:18:32 +08:00
1 parent d2e7eb678a
commit 22b05c91a2
7 files changed
+316 -66

No files matched your search

@@ -30,8 +30,9 @@ class ShippingDocumentProfileAutoFreezeQualification(Base):
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
name='ck_shipping_document_profile_auto_freeze_qualification_status',
),
# 索引名沿用迁移 0aa34b5c6d7e 的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
Index(
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
'ix_ship_doc_prof_auto_freeze_profile_status',
'profile_id', 'status',
),
)
@@ -204,9 +204,10 @@ class ShippingOrderDocumentProfileSuggestionDecision(Base):
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
__table_args__ = (
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
# 约束/索引名沿用迁移的短名;PostgreSQL 标识符上限 63 字符,超长名会导致建库失败。
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'),
Index('ix_order_profile_suggestion_revision', 'profile_id', 'revision_no'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -238,8 +239,8 @@ class ShippingOrderDocumentProfileValidationRun(Base):
name='ck_shipping_order_document_profile_validation_runs_type',
),
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
Index('ix_order_profile_validation_created', 'profile_id', 'created_at'),
Index('ix_order_profile_validation_checksum', 'profile_id', 'definition_checksum'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -268,10 +269,10 @@ class ShippingOrderDocumentProfilePublishCheckReport(Base):
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
__table_args__ = (
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
Index('ix_sodppcr_profile_created', 'profile_id', 'created_at'),
Index('ix_sodppcr_report_no', 'report_no', unique=True),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -7,7 +7,8 @@ backend/app/services/lean_training_push_service.py
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示与考核口径为本任务首次推送的视频
(上一期已推送视频不重复展示、不要求重学,见 lean_training_service._own_pushed_video_ids);
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
企微 event_key 按"批次区间"幂等防止重复打扰(推送后的延期提醒与排程扫描共用"每人每天最多一条"去重,
由 lean_training_reminder_service 统一生成事件键);每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
"""
@@ -235,10 +236,10 @@ def push_lean_training_videos(
)
db.session.add(log)
db.session.commit()
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒
# [STEP 4] 消息推送规则:本批推送成功后立马对任务中"已延期"(过截止未提交)的受训人员发送企微提醒;
# 延期提醒与排程扫描共用"每人每天最多一条"判定(event_key 由提醒服务按北京日期统一生成)
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)
@@ -4,12 +4,15 @@ backend/app/services/lean_training_reminder_service.py
用途:执行精益管理周度培训的企微提醒生成与发送。
依赖:精益培训任务/完成/提醒模型、User、wecom_notify。
逻辑:排程按周日截止、周一/周三/周五催学规则写入幂等提醒,再由统一企微服务发送并落审计。
催办文案携带期次标签(第N期+周次区间)供员工区分期次;多期过期任务对同一员工合并为
一条汇总提醒,且所有自动催办(排程扫描/推送后延期)共用"每人每天最多一条"判定,
历史期任务过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天后停止催办。
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from datetime import date, datetime, time, timedelta, timezone
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
@@ -19,9 +22,75 @@ from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainin
from app.services.lean_training_service import (
resolve_lean_training_jump_agent_id,
target_user_ids_for_task,
week_index_for_task,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
# 历史期任务停止催办的宽限天数:过截止超过该天数后不再发送任何逾期/延期提醒。
# 任务仍保持 published 供管理端查询与统计,仅静默催办(2026-09-30 用户反馈旧期任务永久催办造成重复打扰)。
OVERDUE_REMINDER_STOP_AFTER_DAYS = 100
# 周中催学发送日(周一/周三/周五,Asia/Shanghai),与排程契约一致。
OVERDUE_REMINDER_WEEKDAYS = {0, 2, 4}
def _period_labels(task: LeanTrainingWeeklyTask) -> tuple[str, str]:
"""
返回周任务的期次标签二元组,供催办文案区分期次。
用途:多期任务并存扫描时,各期提醒文案完全相同,员工完成当期后仍会收到历史期催办,
无法分辨提醒归属哪一期而误以为系统误推(2026-09-30 正式环境用户反馈)。
期号与学员端"第N期"口径一致(week_key 全局升序,最早为第 1 期)。
Returns:
(短标签「第N期」用于标题后缀, 完整标签「第N期(MM-DD至MM-DD)」用于内容前缀);
week_key 脏数据解析失败时返回 ("", ""),调用方回退历史文案,提醒不因标签失败而中断。
"""
try:
week_start = date.fromisoformat(task.week_key)
except ValueError:
return "", ""
week_end = week_start + timedelta(days=6)
index = week_index_for_task(task)
return f"第{index}期", f"第{index}期({week_start.strftime('%m-%d')}至{week_end.strftime('%m-%d')})"
def _overdue_event_key(now: datetime) -> str | None:
"""
返回催办轮次唯一键(overdue-<北京日期>),仅周一/周三/周五返回键,其余日期返回 None。
排程扫描与推送后延期提醒共用同一键空间:同一员工同一自然天的全部自动催办只允许一条,
LeanTrainingReminder 唯一约束 + 发送前"当天已催办"前置查询双重拦截重复推送
(2026-09-30 用户反馈同一员工同一天收到多条相同催办)。
"""
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
if local_now.weekday() not in OVERDUE_REMINDER_WEEKDAYS:
return None
return f"overdue-{local_now.date().isoformat()}"
def _is_overdue_active(task: LeanTrainingWeeklyTask, now: datetime) -> bool:
"""判断任务处于"可催办"窗口:已过截止、且过截止未超过宽限期(超期历史期停止催办)。"""
return task.due_at < now <= task.due_at + timedelta(days=OVERDUE_REMINDER_STOP_AFTER_DAYS)
def _has_overdue_reminder_today(user_id: int, now: datetime) -> bool:
"""
判断员工北京时间当天是否已收到过任意精益自动催办(逾期/延期),实现"每人每天最多一条"。
用途:多期过期任务并存、排程扫描与批次推送两条催办路径同天先后执行时,
后执行的一方据此跳过,避免同一员工同一天收到多条相同催办。
"""
local_tz = resolve_schedule_tzinfo("Asia/Shanghai")
local_now = now.replace(tzinfo=timezone.utc).astimezone(local_tz)
day_floor_utc = to_utc_naive(datetime.combine(local_now.date(), time(0, 0, 0), tzinfo=local_tz))
existing = db.session.execute(
select(LeanTrainingReminder.id).where(
LeanTrainingReminder.recipient_user_id == user_id,
LeanTrainingReminder.event_key.like("overdue-%"),
LeanTrainingReminder.created_at >= day_floor_utc,
).limit(1)
).scalar_one_or_none()
return existing is not None
def _send_reminder(
@@ -126,6 +195,9 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
if forbidden_ids:
raise ValueError("Some reminder recipients are outside the task target")
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
short_label, full_label = _period_labels(task)
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
for recipient in recipients:
if recipient.id in completed_user_ids:
totals["skipped"] += 1
@@ -135,8 +207,8 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
recipient=recipient,
event_key=f"targeted-{uuid.uuid4().hex}",
event_type="training_lean_targeted_reminder",
title="精益管理培训定向提醒",
content="您尚未完成本周精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
title=f"精益管理培训定向提醒{title_suffix}",
content=f"您尚未完成{content_prefix}精益管理培训,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
totals["created"] += result != "skipped"
@@ -148,25 +220,27 @@ def send_targeted_reminders(task_id: int, user_ids: list[int], *, now: datetime
def notify_overdue_users_after_push(
task: LeanTrainingWeeklyTask,
*,
event_key: str,
current: datetime | None = None,
) -> dict[str, int]:
"""
视频批次推送成功后,立即对该任务中"已延期"(已过截止时间且未提交感悟)的受训人员发送企微提醒。
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒(与批次 event_key 绑定幂等,同批重推不重复打扰)。
对应周任务消息推送规则:每次推送周任务成功后立马推送延期提醒。
去重规则(2026-09-30 用户反馈消息太多):与排程扫描共用 overdue-<北京日期> 事件键与
"每人每天最多一条自动催办"前置判定——员工当天已收到过任意精益催办(含排程扫描、
其它批次延期提醒)时本路径静默跳过,确保同一员工同一自然天只收到一条催办。
已过截止超过 OVERDUE_REMINDER_STOP_AFTER_DAYS 天的历史期任务不再发送(历史期补推不再催办旧账)。
Args:
task: 刚完成视频推送的周任务(必须已发布)。
event_key: 幂等键,建议携带批次区间(如 overdue-after-push-0-2),与推送批次一一对应。
current: 覆盖当前时间(UTC naive,测试用)。
Returns:
{"created", "sent", "skipped", "failed"} 汇总统计。
"""
now = current or utc_now_naive()
totals = {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
# 未过截止时间不存在"已延期"人员,直接返回,避免无意义扫描
if now <= task.due_at:
# 未过截止时间不存在"已延期"人员;超宽限期的历史期任务同样跳过,避免对旧账无限催办
if not _is_overdue_active(task, now):
return totals
completed_user_ids = set(
db.session.execute(
@@ -178,14 +252,21 @@ def notify_overdue_users_after_push(
)
overdue_ids = target_user_ids_for_task(task) - completed_user_ids
users = db.session.execute(select(User).where(User.id.in_(overdue_ids), User.status == "active")).scalars().all() if overdue_ids else []
event_key = _overdue_event_key(now)
short_label, full_label = _period_labels(task)
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
for user in users:
if _has_overdue_reminder_today(user.id, now):
totals["skipped"] += 1
continue
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_key=event_key or f"overdue-after-push-{uuid.uuid4().hex}",
event_type="training_lean_overdue",
title="精益管理培训延期提醒",
content="您本周精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
title=f"精益管理培训延期提醒{title_suffix}",
content=f"您{content_prefix}精益管理培训已延期,尚未完成视频观看与学习感悟提交,请尽快完成。",
current=now,
)
totals["created"] += result != "skipped"
@@ -194,45 +275,65 @@ def notify_overdue_users_after_push(
return totals
def _event_key(task: LeanTrainingWeeklyTask, now: datetime) -> str | None:
"""按周日截止后的周一、周三、周五计算本轮逾期提醒唯一键。"""
if now <= task.due_at:
return None
local_now = now.replace(tzinfo=timezone.utc).astimezone(resolve_schedule_tzinfo("Asia/Shanghai"))
weekday = local_now.weekday()
if weekday not in {0, 2, 4}:
return None
return f"overdue-{local_now.date().isoformat()}"
def run_lean_training_reminders(*, now: datetime | None = None) -> dict[str, int]:
"""扫描未完成人员并发送本轮提醒,重复运行由唯一约束确保不重复推送。"""
"""扫描全部已发布任务,按"每人每天一条"发送合并逾期提醒,重复运行由当天去重与唯一约束兜底。
合并规则(2026-09-30 用户反馈多期并存时每人收到多条相同催办):周一/周三/周五扫描时,
同一员工名下全部可催办期次(已过截止且未超宽限期、本人未完成)合并为一条提醒——单期文案
携带该期次标签,多期汇总各期标签并注明期数;卡片跳转定位到其最近一期未完成任务。
提醒文案携带期次标签(第N期+周次区间)供员工区分期次,避免完成当期后仍收到历史期
相同提醒而被误认为系统误推。
"""
current = now or utc_now_naive()
event_key = _overdue_event_key(current)
if not event_key:
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
tasks = db.session.execute(select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")).scalars().all()
created = sent = skipped = failed = 0
# [STEP 1] 汇总各员工全部可催办期次:已过截止、未超宽限期、本人属于受训对象且未完成
pending: dict[int, list[LeanTrainingWeeklyTask]] = {}
for task in tasks:
event_key = _event_key(task, current)
if not event_key:
if not _is_overdue_active(task, current):
continue
completed_user_ids = set(db.session.execute(select(LeanTrainingCompletion.user_id).where(LeanTrainingCompletion.weekly_task_id == task.id, LeanTrainingCompletion.status == "completed")).scalars())
target_user_ids = target_user_ids_for_task(task)
users = db.session.execute(select(User).where(User.id.in_(target_user_ids - completed_user_ids))).scalars().all() if target_user_ids else []
for user in users:
result = _send_reminder(
task=task,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title="精益管理培训逾期提醒",
content="本周精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。",
current=current,
)
created += result != "skipped"
if result == "sent":
sent += 1
elif result == "failed":
failed += 1
else:
skipped += 1
for user_id in sorted(target_user_ids_for_task(task) - completed_user_ids):
pending.setdefault(user_id, []).append(task)
if not pending:
return {"created": 0, "sent": 0, "skipped": 0, "failed": 0}
# [STEP 2] 每人仅发一条:按周次倒序取最近一期未完成任务作卡片跳转主任务,多期时汇总各期标签
users = db.session.execute(select(User).where(User.id.in_(list(pending)))).scalars().all()
created = sent = skipped = failed = 0
for user in users:
if _has_overdue_reminder_today(user.id, current):
skipped += 1
continue
user_tasks = sorted(pending[user.id], key=lambda item: item.week_key, reverse=True)
primary = user_tasks[0]
period_labels = [_period_labels(item) for item in reversed(user_tasks)]
if len(user_tasks) == 1:
short_label, full_label = period_labels[0]
title_suffix = f"({short_label})" if short_label else ""
content_prefix = full_label if full_label else "本周"
title = f"精益管理培训逾期提醒{title_suffix}"
content = f"{content_prefix}精益管理培训尚未完成,请观看指定视频并提交不少于50字的学习感悟。"
else:
joined_labels = "、".join(full for _, full in period_labels if full)
title = f"精益管理培训逾期提醒(共{len(user_tasks)}期未完成)"
content = f"您共有{len(user_tasks)}期精益管理培训尚未完成:{joined_labels},请观看指定视频并提交不少于50字的学习感悟。"
result = _send_reminder(
task=primary,
recipient=user,
event_key=event_key,
event_type="training_lean_overdue",
title=title,
content=content,
current=current,
)
created += result != "skipped"
if result == "sent":
sent += 1
elif result == "failed":
failed += 1
else:
skipped += 1
db.session.commit()
return {"created": created, "sent": sent, "skipped": skipped, "failed": failed}