feat(training): 推送管理:学员开课通知、周一讲师汇总与企微推送闭环
[2026-11 推学员/推讲师需求] 培训提醒统一走 tr_notifications outbox(站内流水 +
企微 push_status 投递),推送文案可配置,管理端可查逐人投递明细。
后端 internal/application/service:
- training_notify.go(重写)推送管理核心:
- 学员开课通知 scene=session_notice_student:immediate 场次在名单保存/课件上传后
立即入队,day_before 场次由调度器 T-1 且课件就绪时入队;课件门控 +
(tenant,target,scene,ref) 唯一索引幂等,一人一场最多一条
- 周一讲师未完成汇总 scene=remind_monthly_lecturer:北京时间周一发送(时点可配),
轮次键 YYYY-MM-Wn 幂等,场次全部结束自然停推
- 提醒推送文案模板 notify_text_templates:配置中心可编辑,{占位符} 替换渲染,
空字段回落内置默认
- ListPushLogs 推送记录:逐人投递明细(push_status/重试/错误 + 员工姓名工号映射)
- training_scheduler.go:
- 学员提醒收敛到 session_notice_student 单通道,讲师 T-N 授课提醒与
课程维护提醒(临近开课仍缺课件)保持
- 新增每周一讲师未完成汇总生成(租户开关 + 发送小时可配)
- 企微外箱消费 dispatchPending:FOR UPDATE SKIP LOCKED 多实例安全,
sending 超时回收,重试上限置 dead
- PushTestNotification 推送链路自测(校验凭据与 userid 绑定)
- training_ops.go:默认规则种子追加企微推送开关键/周一讲师键/提醒文案默认模板
前端 frontend/src/views/training:
- RulePanel.vue:配置中心新增「提醒推送文案」编辑卡与「推送记录」明细表
(场景筛选、手动触发周一讲师提醒)
- CoursePanel.vue:场次通知模式新增 immediate「名单/课件就绪后立即推送」
- CourseCatalog.vue:「我的课程」角色标记(我主讲/我参加)、最近场次排期排序、
待维护统计改橙色(与草稿一致)
- MemberPanel.vue:员工档案支持企微账号绑定(培训提醒推送目标)
测试:training_notify_test.go(模板解析/占位符渲染)、training_scheduler_test.go
(生成幂等/课件门控/停推开关/投递结果/测试推送/文案渲染),go test 全部通过。
This commit is contained in:
1 parent
7ec21f35b0
commit
e378e8b7fd
10 files changed
+11344
No files matched your search
@@ -0,0 +1,613 @@
|
||||
// training_notify.go 推送管理核心(2026-11 推学员/推讲师需求)。
|
||||
//
|
||||
// 三条链路,统一走 tr_notifications outbox(站内流水 + 企微 push_status 投递):
|
||||
// 1. 学员开课通知 scene=session_notice_student,ref=场次 ID:
|
||||
// immediate 场次在名单保存/课件上传后立即入队;day_before 场次由
|
||||
// TrainingScheduler 在开课前 1 天推送(课件门控,上传后本文件补推钩子兜底);
|
||||
// (tenant,target,scene,ref) 唯一索引幂等,一人一场最多一条。
|
||||
// 2. 周一讲师未完成汇总提醒 scene=remind_monthly_lecturer,ref=YYYY-MM-Wn:
|
||||
// TrainingScheduler 每周 N(北京时间 09:00,规则可配)扫描当月仍有未结束
|
||||
// 场次的讲师;场次全部结束即停推(收件人集合自然过滤);手动触发共用本文件
|
||||
// 的轮次键,幂等防重。
|
||||
// 3. 推送记录:管理端逐人明细(tr_notifications push_status + 员工姓名映射)。
|
||||
//
|
||||
// 手动推送(NotifySessionStudents/RunWeeklyLecturerReminders)只写通知行,
|
||||
// 不直接调企微:运行中的 TrainingScheduler dispatchPending 消费 pending 行。
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// 周一讲师汇总提醒的规则键(ruleKeyNotifyWeeklyLecturer* 定义在
|
||||
// training_scheduler.go,同包共享);defaultWeeklyRemindHour 与需求"每周一 09:00"
|
||||
// 一致(北京时间)。pushLogDefaultLimit 推送记录默认拉取条数。
|
||||
const (
|
||||
defaultWeeklyRemindHour = 9
|
||||
pushLogDefaultLimit = 200
|
||||
)
|
||||
|
||||
// beijingZone 需求口径统一 Asia/Shanghai(周次/发送时点不随服务器时区漂移)。
|
||||
var beijingZone = time.FixedZone("Asia/Shanghai", 8*3600)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 规则读取
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// loadPushEnabled reads notify_push_enabled (默认 true):false 时新入队的通知行
|
||||
// 只保留站内流水,push_status 置空不进企微外箱。
|
||||
func (s *trainingService) loadPushEnabled(ctx context.Context, tenantID uint64) bool {
|
||||
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if rule.RuleKey == ruleKeyNotifyPushEnabled {
|
||||
var enabled bool
|
||||
if json.Unmarshal(rule.RuleValue, &enabled) == nil {
|
||||
return enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// weeklyLecturerRule reads the Monday lecturer reminder policy from
|
||||
// tr_rule_configs:组合键 notify_weekly_lecturer({"enabled","hour"},配置中心卡)
|
||||
// 优先;独立键 notify_weekly_lecturer_enabled / notify_weekly_remind_hour 兼容;
|
||||
// 缺省开、09:00(北京时间)。
|
||||
func (s *trainingService) weeklyLecturerRule(ctx context.Context, tenantID uint64) (bool, int) {
|
||||
enabled, hour := true, defaultWeeklyRemindHour
|
||||
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
|
||||
if err != nil {
|
||||
return enabled, hour
|
||||
}
|
||||
for _, rule := range rules {
|
||||
switch rule.RuleKey {
|
||||
case ruleKeyNotifyWeeklyLecturer:
|
||||
var combined struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
Hour *int `json:"hour"`
|
||||
}
|
||||
if json.Unmarshal(rule.RuleValue, &combined) == nil {
|
||||
if combined.Enabled != nil {
|
||||
enabled = *combined.Enabled
|
||||
}
|
||||
if combined.Hour != nil && *combined.Hour >= 0 && *combined.Hour <= 23 {
|
||||
hour = *combined.Hour
|
||||
}
|
||||
}
|
||||
case ruleKeyNotifyWeeklyLecturerEnabled:
|
||||
var v bool
|
||||
if json.Unmarshal(rule.RuleValue, &v) == nil {
|
||||
enabled = v
|
||||
}
|
||||
case ruleKeyNotifyWeeklyRemindHour:
|
||||
var v int
|
||||
if json.Unmarshal(rule.RuleValue, &v) == nil && v >= 0 && v <= 23 {
|
||||
hour = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return enabled, hour
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 推送文案模板([2026-11 需求] 配置中心「提醒推送文案」可编辑,空字段回落默认)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// notifyTextTemplates 各提醒场景的文案模板,占位符形如 {course}/{time};
|
||||
// 只做占位符替换不引入富模板语法,避免配置中心编辑出语法错误。
|
||||
type notifyTextTemplates struct {
|
||||
// 学员开课通知(scene=session_notice_student):站内标题与内容
|
||||
StudentNoticeTitle string `json:"student_notice_title"`
|
||||
StudentNoticeContent string `json:"student_notice_content"`
|
||||
// 讲师授课提醒(T-N):通知标题前缀与企微 markdown 结尾文案
|
||||
//(标题自动追加「:课程名」,无需占位符;结尾文案同时用于 T-1 学员企微消息)
|
||||
LecturerOpenTitle string `json:"lecturer_open_title"`
|
||||
LecturerOpenFooter string `json:"lecturer_open_footer"`
|
||||
// 课程维护提醒(临近开课仍缺课件):通知标题前缀与结尾文案
|
||||
LecturerMaintainTitle string `json:"lecturer_maintain_title"`
|
||||
LecturerMaintainFooter string `json:"lecturer_maintain_footer"`
|
||||
// 周一讲师未完成汇总提醒:标题与内容
|
||||
WeeklyTitle string `json:"weekly_title"`
|
||||
WeeklyContent string `json:"weekly_content"`
|
||||
}
|
||||
|
||||
// 内置默认文案(与历史硬编码逐字一致;{lecturer} 缺讲师时渲染为「待定」)。
|
||||
const (
|
||||
defaultStudentNoticeTitle = "培训开课通知"
|
||||
defaultStudentNoticeContent = "您被点名参加「{course}」培训:{time},{place},讲师:{lecturer}。请准时参加。"
|
||||
defaultLecturerOpenTitle = "授课提醒"
|
||||
defaultLecturerOpenFooter = "请准时参加,详情见培训平台。"
|
||||
defaultLecturerMaintainTitle = "课程维护提醒"
|
||||
defaultLecturerMaintainFooter = "该课程尚未上传课件/学习材料,请尽快登录培训平台补齐,以免影响学员课前学习。"
|
||||
defaultWeeklyTitle = "{year}年{month}月教育训练(第{week}周提醒)"
|
||||
defaultWeeklyContent = "{month} 月已进入第 {week} 周({week_start} 至 {week_end}),您本月仍有 {count} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
|
||||
)
|
||||
|
||||
func defaultNotifyTextTemplates() notifyTextTemplates {
|
||||
return notifyTextTemplates{
|
||||
StudentNoticeTitle: defaultStudentNoticeTitle,
|
||||
StudentNoticeContent: defaultStudentNoticeContent,
|
||||
LecturerOpenTitle: defaultLecturerOpenTitle,
|
||||
LecturerOpenFooter: defaultLecturerOpenFooter,
|
||||
LecturerMaintainTitle: defaultLecturerMaintainTitle,
|
||||
LecturerMaintainFooter: defaultLecturerMaintainFooter,
|
||||
WeeklyTitle: defaultWeeklyTitle,
|
||||
WeeklyContent: defaultWeeklyContent,
|
||||
}
|
||||
}
|
||||
|
||||
// parseNotifyTextTemplates 解析租户配置(空字段回落默认,解析失败整体用默认);
|
||||
// trainingService(经 repo)与 TrainingScheduler(直查 db)共用。
|
||||
func parseNotifyTextTemplates(raw []byte) notifyTextTemplates {
|
||||
t := defaultNotifyTextTemplates()
|
||||
var saved notifyTextTemplates
|
||||
if len(raw) == 0 || json.Unmarshal(raw, &saved) != nil {
|
||||
return t
|
||||
}
|
||||
fill := func(dst *string, v string) {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
*dst = v
|
||||
}
|
||||
}
|
||||
fill(&t.StudentNoticeTitle, saved.StudentNoticeTitle)
|
||||
fill(&t.StudentNoticeContent, saved.StudentNoticeContent)
|
||||
fill(&t.LecturerOpenTitle, saved.LecturerOpenTitle)
|
||||
fill(&t.LecturerOpenFooter, saved.LecturerOpenFooter)
|
||||
fill(&t.LecturerMaintainTitle, saved.LecturerMaintainTitle)
|
||||
fill(&t.LecturerMaintainFooter, saved.LecturerMaintainFooter)
|
||||
fill(&t.WeeklyTitle, saved.WeeklyTitle)
|
||||
fill(&t.WeeklyContent, saved.WeeklyContent)
|
||||
return t
|
||||
}
|
||||
|
||||
// loadNotifyTextTemplates 读取配置中心 notify_text_templates(缺行 = 全默认)。
|
||||
func (s *trainingService) loadNotifyTextTemplates(ctx context.Context, tenantID uint64) notifyTextTemplates {
|
||||
rules, err := s.repo.ListRuleConfigs(ctx, tenantID)
|
||||
if err != nil {
|
||||
return defaultNotifyTextTemplates()
|
||||
}
|
||||
for _, rule := range rules {
|
||||
if rule.RuleKey == ruleKeyNotifyTextTemplates {
|
||||
return parseNotifyTextTemplates(rule.RuleValue)
|
||||
}
|
||||
}
|
||||
return defaultNotifyTextTemplates()
|
||||
}
|
||||
|
||||
// renderNotifyTemplate {name} 占位符替换;模板为空返回空串,未提供的占位符原样保留。
|
||||
func renderNotifyTemplate(tpl string, vars map[string]string) string {
|
||||
if tpl == "" {
|
||||
return ""
|
||||
}
|
||||
pairs := make([]string, 0, len(vars)*2)
|
||||
for k, v := range vars {
|
||||
pairs = append(pairs, "{"+k+"}", v)
|
||||
}
|
||||
return strings.NewReplacer(pairs...).Replace(tpl)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 学员开课通知(immediate 立即推 / day_before 调度器推,共用 scene 幂等)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// sessionMaterialsReady 课件门控:课程下已上传至少一份课件(需求:老师上传课件
|
||||
// 及相关信息后方可通知学员)。
|
||||
func (s *trainingService) sessionMaterialsReady(ctx context.Context, tenantID uint64, courseID string) bool {
|
||||
if courseID == "" {
|
||||
return false
|
||||
}
|
||||
materials, err := s.repo.ListMaterials(ctx, tenantID, courseID)
|
||||
return err == nil && len(materials) > 0
|
||||
}
|
||||
|
||||
// sessionNoticeTargets resolves the roster's platform user IDs for a session
|
||||
// (tr_enrollments.member_id → org_employees.user_id,去重去空)。
|
||||
func (s *trainingService) sessionNoticeTargets(ctx context.Context, tenantID uint64, sessionID string) ([]string, error) {
|
||||
enrolls, err := s.repo.ListEnrollments(ctx, tenantID, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
out := make([]string, 0, len(enrolls))
|
||||
for _, e := range enrolls {
|
||||
member, err := s.repo.GetMember(ctx, tenantID, e.MemberID)
|
||||
if err != nil || member == nil || member.UserID == "" || seen[member.UserID] {
|
||||
continue
|
||||
}
|
||||
seen[member.UserID] = true
|
||||
out = append(out, member.UserID)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// sessionNoticeText 组装学员开课通知文案(时间/地点或线上链接/讲师)。
|
||||
// [2026-11 需求] 文案模板在配置中心「提醒推送文案」可编辑;占位符:
|
||||
// {course} 课程名 / {time} 开课时间 / {place} 地点或线上说明 / {lecturer} 讲师(缺省渲染「待定」)。
|
||||
func (s *trainingService) sessionNoticeText(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession) (string, string) {
|
||||
courseName := sessionCourseTitle(ctx, s, tenantID, session)
|
||||
place := session.Location
|
||||
if session.OnlineURL != "" {
|
||||
place = "线上会议(链接见课程页)"
|
||||
}
|
||||
lecturerName := "待定"
|
||||
if lecturer, err := s.repo.GetMember(ctx, tenantID, session.LecturerID); err == nil && lecturer != nil && lecturer.UserName != "" {
|
||||
lecturerName = lecturer.UserName
|
||||
}
|
||||
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
|
||||
title := renderNotifyTemplate(tpl.StudentNoticeTitle, map[string]string{"course": courseName})
|
||||
content := renderNotifyTemplate(tpl.StudentNoticeContent, map[string]string{
|
||||
"course": courseName,
|
||||
"time": sessionTimeText(session),
|
||||
"place": place,
|
||||
"lecturer": lecturerName,
|
||||
})
|
||||
return title, content
|
||||
}
|
||||
|
||||
// enqueueSessionNotices 对名单内尚未收到开课通知的学员入队(站内+企微外箱),
|
||||
// 返回本轮新入队条数。已通知过滤 + 唯一索引兜底双重幂等。
|
||||
func (s *trainingService) enqueueSessionNotices(
|
||||
ctx context.Context, tenantID uint64, session *types.TrainingCourseSession, targets []string, push bool,
|
||||
) (int, error) {
|
||||
if len(targets) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeCourseSession, session.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
notified := map[string]bool{}
|
||||
for _, row := range existing {
|
||||
if row.Scene == types.SceneSessionNoticeStudent {
|
||||
notified[row.TargetUserID] = true
|
||||
}
|
||||
}
|
||||
title, content := s.sessionNoticeText(ctx, tenantID, session)
|
||||
now := time.Now()
|
||||
rows := make([]*types.TrainingNotification, 0, len(targets))
|
||||
for _, uid := range targets {
|
||||
if uid == "" || notified[uid] {
|
||||
continue
|
||||
}
|
||||
notified[uid] = true
|
||||
status := ""
|
||||
if push {
|
||||
status = pushStatusPending
|
||||
}
|
||||
rows = append(rows, &types.TrainingNotification{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
TargetUserID: uid,
|
||||
Channel: "inapp",
|
||||
Scene: types.SceneSessionNoticeStudent,
|
||||
Title: title,
|
||||
Content: content,
|
||||
RefType: types.RefTypeCourseSession,
|
||||
RefID: session.ID,
|
||||
SentAt: now,
|
||||
PushStatus: status,
|
||||
})
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if err := s.repo.CreateNotifications(ctx, rows); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
logger.Infof(ctx, "[TrainingNotify] session %s: enqueued %d student notices (push=%v)",
|
||||
session.ID, len(rows), push)
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// dispatchSessionNoticesIfNeeded 名单/课件就绪后的统一入口:
|
||||
// - immediate:课件就绪即推(课件未就绪静默跳过,上传课件后由 afterMaterialUploaded 补推);
|
||||
// - day_before:不立即推(调度器 T-1 负责),但若已进入 24h 窗口(扫描时点已过)
|
||||
// 且课件就绪,降级立即补推,避免学员什么都收不到。
|
||||
func (s *trainingService) dispatchSessionNoticesIfNeeded(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession) {
|
||||
if session == nil || session.Status == types.TrainingSessionCancelled {
|
||||
return
|
||||
}
|
||||
if !s.sessionMaterialsReady(ctx, tenantID, session.CourseID) {
|
||||
return
|
||||
}
|
||||
if session.NotifyMode == types.TrainingNotifyModeDayBefore {
|
||||
start := time.Now()
|
||||
if session.StartAt != nil {
|
||||
start = *session.StartAt
|
||||
}
|
||||
if time.Until(start) > 24*time.Hour {
|
||||
return // 还没到 T-1 窗口,交给调度器
|
||||
}
|
||||
}
|
||||
targets, err := s.sessionNoticeTargets(ctx, tenantID, session.ID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingNotify] session %s targets: %v", session.ID, err)
|
||||
return
|
||||
}
|
||||
if _, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID)); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingNotify] session %s enqueue: %v", session.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// AfterEnrollmentsChanged 名单保存(SetEnrollments)后的通知钩子。
|
||||
func (s *trainingService) AfterEnrollmentsChanged(ctx context.Context, tenantID uint64, sessionID string) {
|
||||
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
|
||||
if err != nil || session == nil {
|
||||
return
|
||||
}
|
||||
s.dispatchSessionNoticesIfNeeded(ctx, tenantID, session)
|
||||
}
|
||||
|
||||
// AfterMaterialUploaded 课件上传后的补推钩子:扫描该课程近未来(当月+下月)的
|
||||
// 活跃场次,immediate 场次补推未通知学员;day_before 场次若已进入 T-1 窗口同样
|
||||
// 补推(此时调度器时点已过或即将到点,统一由本钩子兜底,幂等保证不重发)。
|
||||
func (s *trainingService) AfterMaterialUploaded(ctx context.Context, tenantID uint64, courseID string) {
|
||||
now := time.Now()
|
||||
for _, ym := range [][2]int{{now.Year(), int(now.Month())}, {now.Add(30 * 24 * time.Hour).Year(), int(now.Add(30 * 24 * time.Hour).Month())}} {
|
||||
sessions, err := s.repo.ListMonthActiveSessions(ctx, tenantID, ym[0], ym[1])
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingNotify] material hook month %d-%d: %v", ym[0], ym[1], err)
|
||||
continue
|
||||
}
|
||||
for _, session := range sessions {
|
||||
if session.CourseID != courseID {
|
||||
continue
|
||||
}
|
||||
s.dispatchSessionNoticesIfNeeded(ctx, tenantID, session)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NotifySessionStudents 手动"立即推送学员"(配置中心/场次操作):课件门控+
|
||||
// 幂等,返回 (新入队, 已通知跳过) 计数。
|
||||
func (s *trainingService) NotifySessionStudents(ctx context.Context, tenantID uint64, sessionID, operatorID string) (int, int, error) {
|
||||
_ = operatorID
|
||||
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
|
||||
if err != nil || session == nil {
|
||||
return 0, 0, errors.NewNotFoundError("课程场次不存在")
|
||||
}
|
||||
if session.Status == types.TrainingSessionCancelled {
|
||||
return 0, 0, errors.NewBadRequestError("场次已取消,无法通知")
|
||||
}
|
||||
if !s.sessionMaterialsReady(ctx, tenantID, session.CourseID) {
|
||||
return 0, 0, errors.NewBadRequestError("课件尚未上传,请先在课程管理上传课件")
|
||||
}
|
||||
targets, err := s.sessionNoticeTargets(ctx, tenantID, sessionID)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeCourseSession, sessionID)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
notified := map[string]bool{}
|
||||
for _, row := range existing {
|
||||
if row.Scene == types.SceneSessionNoticeStudent {
|
||||
notified[row.TargetUserID] = true
|
||||
}
|
||||
}
|
||||
skipped := 0
|
||||
for _, uid := range targets {
|
||||
if notified[uid] {
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
queued, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID))
|
||||
return queued, skipped, err
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 周一讲师未完成汇总提醒
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// beijingNow returns now in Asia/Shanghai (需求时区口径)。
|
||||
func beijingNow(now time.Time) time.Time {
|
||||
return now.In(beijingZone)
|
||||
}
|
||||
|
||||
// weekOfMonth counts how many Mondays have arrived in the month (含当天,
|
||||
// 按北京时间):2026-10-19 是 10 月第三个周一 → 第 3 周。
|
||||
func weekOfMonth(local time.Time) int {
|
||||
first := time.Date(local.Year(), local.Month(), 1, 0, 0, 0, 0, local.Location())
|
||||
offset := (int(first.Weekday()) + 6) % 7 // 距月初最近的周一已过天数(周一=0)
|
||||
firstMonday := first.AddDate(0, 0, offset)
|
||||
if local.Before(firstMonday) {
|
||||
return 1
|
||||
}
|
||||
return int(local.Sub(firstMonday).Hours()/24)/7 + 1
|
||||
}
|
||||
|
||||
// monthWeekRefID builds the monthly reminder round key, e.g. "2026-11-W3".
|
||||
func monthWeekRefID(local time.Time) string {
|
||||
return fmt.Sprintf("%04d-%02d-W%d", local.Year(), int(local.Month()), weekOfMonth(local))
|
||||
}
|
||||
|
||||
// pendingMonthlyLecturers 汇总"当月仍有未结束场次"的讲师:
|
||||
// key=lecturer member id,value=未结束(结束时间晚于 now)场次数。
|
||||
// 场次全部结束的讲师不在集合里 → 天然实现"完成即停推";无场次的讲师也不推。
|
||||
func (s *trainingService) pendingMonthlyLecturers(
|
||||
ctx context.Context, tenantID uint64, year, month int, now time.Time,
|
||||
) (map[string]int, error) {
|
||||
sessions, err := s.repo.ListMonthActiveSessions(ctx, tenantID, year, month)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pending := map[string]int{}
|
||||
for _, sess := range sessions {
|
||||
if sess.LecturerID == "" {
|
||||
continue
|
||||
}
|
||||
end := now.Add(time.Nanosecond)
|
||||
if sess.EndAt != nil {
|
||||
end = *sess.EndAt
|
||||
} else if sess.StartAt != nil {
|
||||
end = *sess.StartAt
|
||||
}
|
||||
if !end.After(now) {
|
||||
continue // 已结束,不算未完成
|
||||
}
|
||||
pending[sess.LecturerID]++
|
||||
}
|
||||
return pending, nil
|
||||
}
|
||||
|
||||
// enqueueWeeklyLecturerReminders 生成一轮周一讲师汇总提醒(不判断发送窗口,
|
||||
// 由调度器/手动触发各自把关),返回新入队条数。轮次键 ref=YYYY-MM-Wn 幂等,
|
||||
// 同一周内重复触发(定时+手动)不重发。
|
||||
func (s *trainingService) enqueueWeeklyLecturerReminders(
|
||||
ctx context.Context, tenantID uint64, now time.Time, push bool,
|
||||
) (int, error) {
|
||||
local := beijingNow(now)
|
||||
refID := monthWeekRefID(local)
|
||||
existing, err := s.repo.ListNotificationsByRef(ctx, tenantID, types.RefTypeMonth, refID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
notified := map[string]bool{}
|
||||
for _, row := range existing {
|
||||
if row.Scene == types.SceneRemindMonthlyLecturer {
|
||||
notified[row.TargetUserID] = true
|
||||
}
|
||||
}
|
||||
pending, err := s.pendingMonthlyLecturers(ctx, tenantID, local.Year(), int(local.Month()), now)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// [2026-11 需求] 文案模板在配置中心「提醒推送文案」可编辑;占位符:
|
||||
// {year} 年 / {month} 月 / {week} 当月第几周 / {week_start} {week_end} 本周起止(MM-DD) / {count} 未结束场次数
|
||||
tpl := s.loadNotifyTextTemplates(ctx, tenantID)
|
||||
baseVars := map[string]string{
|
||||
"year": strconv.Itoa(local.Year()),
|
||||
"month": strconv.Itoa(int(local.Month())),
|
||||
"week": strconv.Itoa(weekOfMonth(local)),
|
||||
"week_start": "",
|
||||
"week_end": "",
|
||||
}
|
||||
weekStart := local.AddDate(0, 0, -int(local.Weekday()+6)%7)
|
||||
weekEnd := weekStart.AddDate(0, 0, 6)
|
||||
baseVars["week_start"] = weekStart.Format("01-02")
|
||||
baseVars["week_end"] = weekEnd.Format("01-02")
|
||||
title := renderNotifyTemplate(tpl.WeeklyTitle, baseVars)
|
||||
rows := make([]*types.TrainingNotification, 0, len(pending))
|
||||
for lecturerMemberID, count := range pending {
|
||||
member, err := s.repo.GetMember(ctx, tenantID, lecturerMemberID)
|
||||
if err != nil || member == nil || member.UserID == "" {
|
||||
continue
|
||||
}
|
||||
if notified[member.UserID] {
|
||||
continue
|
||||
}
|
||||
notified[member.UserID] = true
|
||||
vars := make(map[string]string, len(baseVars)+1)
|
||||
for k, v := range baseVars {
|
||||
vars[k] = v
|
||||
}
|
||||
vars["count"] = strconv.Itoa(count)
|
||||
content := renderNotifyTemplate(tpl.WeeklyContent, vars)
|
||||
status := ""
|
||||
if push {
|
||||
status = pushStatusPending
|
||||
}
|
||||
rows = append(rows, &types.TrainingNotification{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
TargetUserID: member.UserID,
|
||||
Channel: "inapp",
|
||||
Scene: types.SceneRemindMonthlyLecturer,
|
||||
Title: title,
|
||||
Content: content,
|
||||
RefType: types.RefTypeMonth,
|
||||
RefID: refID,
|
||||
SentAt: now,
|
||||
PushStatus: status,
|
||||
})
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if err := s.repo.CreateNotifications(ctx, rows); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
logger.Infof(ctx, "[TrainingNotify] weekly lecturer reminder %s: enqueued %d", refID, len(rows))
|
||||
return len(rows), nil
|
||||
}
|
||||
|
||||
// weeklyLecturerDueNow 判断当前北京时间是否处于周一提醒发送窗口
|
||||
// (周一且小时等于配置值;调度器 5 分钟 tick,窗口命中一小时)。
|
||||
func (s *trainingService) weeklyLecturerDueNow(ctx context.Context, tenantID uint64, now time.Time) bool {
|
||||
enabled, hour := s.weeklyLecturerRule(ctx, tenantID)
|
||||
if !enabled {
|
||||
return false
|
||||
}
|
||||
local := beijingNow(now)
|
||||
return local.Weekday() == time.Monday && local.Hour() == hour
|
||||
}
|
||||
|
||||
// RunWeeklyLecturerReminders 手动触发一轮讲师汇总提醒(不看发送窗口,轮次键
|
||||
// 幂等,同周重复点击不重发),返回新入队条数。
|
||||
func (s *trainingService) RunWeeklyLecturerReminders(ctx context.Context, tenantID uint64, operatorID string) (int, error) {
|
||||
_ = operatorID
|
||||
return s.enqueueWeeklyLecturerReminders(ctx, tenantID, time.Now(), s.loadPushEnabled(ctx, tenantID))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 推送记录(管理台逐人明细)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// ListPushLogs 管理端逐人推送明细:tr_notifications 按场景/引用过滤后映射
|
||||
// 收件人姓名与工号(org_employees 联 users 展示名)。
|
||||
func (s *trainingService) ListPushLogs(
|
||||
ctx context.Context, tenantID uint64, scenes []string, refType string, limit int,
|
||||
) ([]*types.TrainingPushLog, error) {
|
||||
if limit <= 0 {
|
||||
limit = pushLogDefaultLimit
|
||||
}
|
||||
rows, err := s.repo.ListPushLogs(ctx, tenantID, scenes, refType, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userIDs := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
userIDs = append(userIDs, row.TargetUserID)
|
||||
}
|
||||
members, _ := s.repo.ListMembersByUserIDs(ctx, tenantID, userIDs)
|
||||
byUser := map[string]*types.TrainingMember{}
|
||||
for _, m := range members {
|
||||
byUser[m.UserID] = m
|
||||
}
|
||||
out := make([]*types.TrainingPushLog, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
item := &types.TrainingPushLog{
|
||||
ID: row.ID,
|
||||
Scene: row.Scene,
|
||||
Title: row.Title,
|
||||
RefType: row.RefType,
|
||||
RefID: row.RefID,
|
||||
TargetUserID: row.TargetUserID,
|
||||
PushStatus: row.PushStatus,
|
||||
PushAttempts: row.PushAttempts,
|
||||
PushedAt: row.PushedAt,
|
||||
PushError: row.PushError,
|
||||
SentAt: row.SentAt,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
if m := byUser[row.TargetUserID]; m != nil {
|
||||
item.TargetName = m.UserName
|
||||
item.EmployeeNo = m.EmployeeNo
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// training_notify_test.go 推送文案模板(配置中心「提醒推送文案」)的解析与渲染。
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseNotifyTextTemplatesFallsBackToDefaults(t *testing.T) {
|
||||
// 缺行/损坏 JSON → 整体内置默认
|
||||
require.Equal(t, defaultNotifyTextTemplates(), parseNotifyTextTemplates(nil))
|
||||
require.Equal(t, defaultNotifyTextTemplates(), parseNotifyTextTemplates([]byte("not json")))
|
||||
|
||||
// 自定义字段生效,空字段回落默认(配置中心"清空即恢复默认")
|
||||
raw, err := json.Marshal(map[string]any{
|
||||
"student_notice_title": "自定义开课标题",
|
||||
"student_notice_content": "",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
got := parseNotifyTextTemplates(raw)
|
||||
require.Equal(t, "自定义开课标题", got.StudentNoticeTitle)
|
||||
require.Equal(t, defaultStudentNoticeContent, got.StudentNoticeContent)
|
||||
require.Equal(t, defaultWeeklyTitle, got.WeeklyTitle)
|
||||
}
|
||||
|
||||
func TestRenderNotifyTemplate(t *testing.T) {
|
||||
require.Equal(t, "", renderNotifyTemplate("", map[string]string{"course": "x"}))
|
||||
require.Equal(t,
|
||||
"您被点名参加「安全培训」培训:11月18日 09:00,大会议室。请准时参加。",
|
||||
renderNotifyTemplate("您被点名参加「{course}」培训:{time},{place}。请准时参加。",
|
||||
map[string]string{"course": "安全培训", "time": "11月18日 09:00", "place": "大会议室"}))
|
||||
// 未提供变量的占位符原样保留(不做删改,便于发现漏配)
|
||||
require.Equal(t, "{a}-x", renderNotifyTemplate("{a}-{b}", map[string]string{"b": "x"}))
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"academy/internal/errors"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 运营闭环补齐:代签到 / 学员取卷 / 代交卷 / 讲师结算 / 规则种子 / 平台用户
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// CheckinFor 讲师/课长/人事代扫码/现场补录:以目标成员身份签到,proxy 标记留痕。
|
||||
func (s *trainingService) CheckinFor(ctx context.Context, tenantID uint64, operatorUserID, token, targetMemberID string, lat, lng float64, channel string) (*types.TrainingSignRecord, error) {
|
||||
if targetMemberID == "" {
|
||||
return nil, errors.NewBadRequestError("缺少代签成员")
|
||||
}
|
||||
target, err := s.repo.GetMember(ctx, tenantID, targetMemberID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("成员不存在")
|
||||
}
|
||||
if target.UserID == operatorUserID {
|
||||
return s.Checkin(ctx, tenantID, operatorUserID, token, lat, lng, channel)
|
||||
}
|
||||
// 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。
|
||||
record, err := s.Checkin(ctx, tenantID, target.UserID, token, lat, lng, "proxy")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// proxy 标记追加留痕(异常复核列表可见)。
|
||||
flags := append(trainingJSONStrings(string(record.AbnormalFlags)), "proxy")
|
||||
record.AbnormalFlags = trainingJSONFromSlice(flags)
|
||||
if err := s.repo.ReviewSignRecord(ctx, record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
// GetPaperForExam 学员答题视图:题目剥离答案与解析;课长/讲师/人事可见完整数据。
|
||||
func (s *trainingService) GetPaperForExam(ctx context.Context, tenantID uint64, userID, paperID string) (*types.TrainingPaper, []*types.TrainingQuestion, error) {
|
||||
paper, err := s.repo.GetPaper(ctx, tenantID, paperID)
|
||||
if err != nil {
|
||||
return nil, nil, errors.NewNotFoundError("试卷不存在")
|
||||
}
|
||||
member, memberErr := s.repo.GetMemberByUserID(ctx, tenantID, userID)
|
||||
isStaff := false
|
||||
if memberErr == nil && member != nil {
|
||||
// 角色按字典权限分配展开后判定(自定义角色继承 hr/lecturer/supervisor 即视为运营人员)。
|
||||
for _, r := range s.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList()) {
|
||||
if r == types.TrainingRoleHR || r == types.TrainingRoleLecturer || r == types.TrainingRoleSupervisor {
|
||||
isStaff = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ids := trainingJSONStrings(string(paper.QuestionIDs))
|
||||
questions, err := s.repo.ListQuestionsByIDs(ctx, tenantID, ids)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
// 按组卷时的题序返回。
|
||||
order := map[string]int{}
|
||||
for i, id := range ids {
|
||||
order[id] = i
|
||||
}
|
||||
sort.Slice(questions, func(i, j int) bool { return order[questions[i].ID] < order[questions[j].ID] })
|
||||
// 展示分值用组卷时按满分 100 自动划分的试卷级分值(旧试卷回退题目自身分值)。
|
||||
if paperScores := paperQuestionScores(paper); paperScores != nil {
|
||||
for _, q := range questions {
|
||||
if v, ok := paperScores[q.ID]; ok {
|
||||
q.Score = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !isStaff {
|
||||
for _, q := range questions {
|
||||
q.Answer = ""
|
||||
q.Analysis = ""
|
||||
}
|
||||
}
|
||||
return paper, questions, nil
|
||||
}
|
||||
|
||||
// SubmitExamFor 监考代交卷:课长/讲师/人事为线下答题的学员录入答卷。
|
||||
func (s *trainingService) SubmitExamFor(ctx context.Context, tenantID uint64, operatorUserID, targetMemberID, paperID string, answers map[string]string) (*types.TrainingExamRecord, error) {
|
||||
if targetMemberID == "" {
|
||||
return nil, errors.NewBadRequestError("缺少交卷成员")
|
||||
}
|
||||
target, err := s.repo.GetMember(ctx, tenantID, targetMemberID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("成员不存在")
|
||||
}
|
||||
paper, err := s.repo.GetPaper(ctx, tenantID, paperID)
|
||||
if err != nil {
|
||||
return nil, errors.NewNotFoundError("试卷不存在")
|
||||
}
|
||||
if target.UserID == operatorUserID {
|
||||
return s.SubmitExam(ctx, tenantID, operatorUserID, paperID, answers)
|
||||
}
|
||||
// 走同一判分逻辑,以目标成员身份落卷。
|
||||
return s.submitExamAs(ctx, tenantID, target, paper, answers)
|
||||
}
|
||||
|
||||
// SettleLecturerScores 结算某月讲师综合分:
|
||||
// 按时开课40%(场次完结率) + 学员评分50%(均值/5) + 互动答疑10%(已回复占比)。
|
||||
func (s *trainingService) SettleLecturerScores(ctx context.Context, tenantID uint64, year, month int, operatorID string) ([]*types.TrainingLecturerScore, error) {
|
||||
if month < 1 || month > 12 {
|
||||
return nil, errors.NewBadRequestError("月份不合法")
|
||||
}
|
||||
weights := trainingJSONMap(s.ruleBytes(ctx, tenantID, types.RuleKeyLecturerScoreWeight))
|
||||
wOnTime := trainingJSONFloat(weights, "on_time", 40)
|
||||
wRating := trainingJSONFloat(weights, "rating", 50)
|
||||
wQA := trainingJSONFloat(weights, "qa", 10)
|
||||
|
||||
stats, err := s.repo.LecturerMonthStats(ctx, tenantID, year, month)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
results := make([]*types.TrainingLecturerScore, 0, len(stats))
|
||||
for _, st := range stats {
|
||||
onTime := 0.0
|
||||
if st.SessionsTotal > 0 {
|
||||
onTime = float64(st.SessionsFinished) / float64(st.SessionsTotal)
|
||||
}
|
||||
avgRating, _ := s.repo.AvgRatingByLecturer(ctx, tenantID, st.LecturerID, year)
|
||||
rating := avgRating / 5.0
|
||||
pendings, _ := s.repo.PendingFeedbacks(ctx, tenantID, st.LecturerID)
|
||||
allFeedbacks, _ := s.repo.ListFeedbacksByLecturer(ctx, tenantID, st.LecturerID, year)
|
||||
qAnswered := 0.0
|
||||
if len(allFeedbacks) > 0 {
|
||||
qAnswered = float64(len(allFeedbacks)-len(pendings)) / float64(len(allFeedbacks))
|
||||
}
|
||||
total := onTime*wOnTime + rating*wRating + qAnswered*wQA
|
||||
score := &types.TrainingLecturerScore{
|
||||
ID: trainingNewID(), TenantID: tenantID, LecturerID: st.LecturerID,
|
||||
Year: year, Month: month,
|
||||
OnTimeScore: mathRound1(onTime * wOnTime),
|
||||
RatingScore: mathRound1(rating * wRating),
|
||||
QAScore: mathRound1(qAnswered * wQA),
|
||||
Total: mathRound1(total),
|
||||
}
|
||||
if err := s.repo.UpsertLecturerScore(ctx, score); err != nil {
|
||||
continue
|
||||
}
|
||||
results = append(results, score)
|
||||
}
|
||||
// 排名。
|
||||
sort.SliceStable(results, func(i, j int) bool { return results[i].Total > results[j].Total })
|
||||
for i, r := range results {
|
||||
r.RankNo = i + 1
|
||||
_ = s.repo.UpsertLecturerScore(ctx, r)
|
||||
}
|
||||
logger.Infof(ctx, "[Training] lecturer scores settled, tenant=%d %d-%02d lecturers=%d operator=%s",
|
||||
tenantID, year, month, len(results), operatorID)
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// defaultRuleSeed 一期默认规则(与落地方案 §11 的建议默认值一致)。
|
||||
// [2026-11 推送管理] 追加企微推送三键,与 training_scheduler.loadNotifyConfig /
|
||||
// training_notify.weeklyLecturerRule 的读取键对齐(缺行时后端有同值兜底,种子只为
|
||||
// 配置中心"初始化默认配置"与高级配置可见性)。
|
||||
func defaultRuleSeed() map[string]string {
|
||||
roleDictRaw, _ := json.Marshal(map[string]any{"roles": types.DefaultRoleDict()})
|
||||
// [2026-11 需求] 提醒推送文案默认模板(配置中心「提醒推送文案」卡)
|
||||
notifyTextRaw, _ := json.Marshal(defaultNotifyTextTemplates())
|
||||
return map[string]string{
|
||||
types.RuleKeyLecturerScoreWeight: `{"on_time":40,"rating":50,"qa":10}`,
|
||||
types.RuleKeyPointRules: `{"required":10,"score_90":10,"score_100":20,"pass":5,"elective":5,"self_study":3}`,
|
||||
types.RuleKeyRemindPolicy: `{"t3":true,"t1":true,"third_week":true,"month_end":true}`,
|
||||
types.RuleKeySignPolicy: `{"late_after_min":15,"geo_radius_m":300,"require_geo":false}`,
|
||||
types.RuleKeyPassLine: `{"default":75}`,
|
||||
types.RuleKeyRollPolicy: `{"escalate_after":2}`,
|
||||
types.RuleKeyRoleDict: string(roleDictRaw),
|
||||
ruleKeyNotifyRemindDays: `[3,1]`,
|
||||
ruleKeyNotifyPushEnabled: `true`,
|
||||
ruleKeyNotifyWeeklyLecturer: `{"enabled":true,"hour":9}`,
|
||||
ruleKeyNotifyTextTemplates: string(notifyTextRaw),
|
||||
}
|
||||
}
|
||||
|
||||
// SeedRuleConfigs 初始化默认规则;已存在的键不覆盖(人事确认后再改)。
|
||||
func (s *trainingService) SeedRuleConfigs(ctx context.Context, tenantID uint64, operatorID string) ([]*types.TrainingRuleConfig, error) {
|
||||
seeded := []*types.TrainingRuleConfig{}
|
||||
for key, raw := range defaultRuleSeed() {
|
||||
if _, err := s.repo.GetRuleConfig(ctx, tenantID, key); err == nil {
|
||||
continue
|
||||
}
|
||||
cfg := &types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
RuleKey: key, RuleValue: types.JSON([]byte(raw)), UpdatedBy: operatorID,
|
||||
}
|
||||
if err := s.repo.UpsertRuleConfig(ctx, cfg); err != nil {
|
||||
continue
|
||||
}
|
||||
seeded = append(seeded, cfg)
|
||||
}
|
||||
logger.Infof(ctx, "[Training] rule configs seeded, tenant=%d count=%d operator=%s", tenantID, len(seeded), operatorID)
|
||||
return seeded, nil
|
||||
}
|
||||
|
||||
// publishOnlineLearningTasks 线上课发布后按部门范围生成学习任务
|
||||
// (必修推送全员/部门批量指派,默认 7 天期限,可配 learning_policy.default_days)。
|
||||
func (s *trainingService) publishOnlineLearningTasks(ctx context.Context, tenantID uint64, course *types.TrainingCourse, operatorID string) {
|
||||
members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining,
|
||||
&types.OrgListQuery{Page: 1, PageSize: 1000})
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Training] learning tasks: list members failed: %v", err)
|
||||
return
|
||||
}
|
||||
// 注意:DeptIDs 是 jsonb,"[]" 的字节长度大于 0,必须按解析后的元素判断范围。
|
||||
scopeDepts := trainingJSONStrings(string(course.DeptIDs))
|
||||
deadlineDays := int(s.ruleFloat(ctx, tenantID, "learning_policy", "default_days", 7))
|
||||
deadline := time.Now().AddDate(0, 0, deadlineDays)
|
||||
created, failed := 0, 0
|
||||
for _, m := range members {
|
||||
if m.Status != "active" {
|
||||
continue
|
||||
}
|
||||
if len(scopeDepts) > 0 {
|
||||
inScope := false
|
||||
for _, d := range scopeDepts {
|
||||
if d == m.DeptID {
|
||||
inScope = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !inScope {
|
||||
continue
|
||||
}
|
||||
}
|
||||
task := &types.TrainingLearningTask{
|
||||
ID: trainingNewID(), TenantID: tenantID,
|
||||
CourseID: course.ID, MemberID: m.ID,
|
||||
Deadline: &deadline,
|
||||
RemindRule: "every_3_days",
|
||||
Status: types.TrainingLearningPending,
|
||||
}
|
||||
if err := s.repo.UpsertLearningTask(ctx, task); err != nil {
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
created++
|
||||
_ = s.Notify(ctx, tenantID, m.UserID, "learning_task",
|
||||
"线上学习任务", fmt.Sprintf("课程《%s》已发布,请在 %d 天内完成学习。", course.Name, deadlineDays),
|
||||
"course", course.ID)
|
||||
}
|
||||
logger.Infof(ctx, "[Training] online learning tasks created, tenant=%d course=%s count=%d failed=%d operator=%s",
|
||||
tenantID, course.ID, created, failed, operatorID)
|
||||
}
|
||||
@@ -0,0 +1,760 @@
|
||||
// TrainingScheduler pushes scheduled training reminders to WeCom.
|
||||
//
|
||||
// It runs two deterministic (no-LLM) steps on a ticker, mirroring the
|
||||
// AutomationService tick loop:
|
||||
//
|
||||
// 1. generateReminders — scans tr_course_sessions inside the horizon and
|
||||
// writes tr_notifications rows for T-N day session reminders (students
|
||||
// via tr_enrollments, lecturer via lecturer_id) and for the
|
||||
// "maintain your course" lecturer reminder when the course has no
|
||||
// materials. Idempotency is enforced by the partial unique index
|
||||
// idx_tr_notifications_dedup (tenant_id, target_user_id, scene, ref_id).
|
||||
// 2. dispatchPending — the WeCom outbox consumer: claims pending rows with
|
||||
// FOR UPDATE SKIP LOCKED (multi-instance safe), resolves the tenant's
|
||||
// webhook-mode WeCom IM channel credentials plus each user's
|
||||
// org_employees.wecom_userid, sends markdown via /cgi-bin/message/send
|
||||
// and records the result.
|
||||
//
|
||||
// Credentials are reused from the tenant's IM integration: a wecom channel
|
||||
// in webhook (self-built app) mode. websocket-mode smart-bot credentials
|
||||
// cannot call message/send and are ignored.
|
||||
//
|
||||
// The WeCom client construction is injected (WecomPushBackend, wired to
|
||||
// internal/im/wecompush.Backend by the container) so this file never
|
||||
// imports internal/im: internal/im's in-package tests import this package,
|
||||
// and a service → im edge creates an import cycle in the im test binary.
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"academy/internal/application/repository"
|
||||
"academy/internal/logger"
|
||||
"academy/internal/runtime"
|
||||
"academy/internal/types"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// tr_notification push_status values (see migration 000144).
|
||||
const (
|
||||
pushStatusPending = "pending"
|
||||
pushStatusSending = "sending"
|
||||
pushStatusSent = "sent"
|
||||
pushStatusSkipped = "skipped"
|
||||
pushStatusDead = "dead"
|
||||
)
|
||||
|
||||
// Tenant-configurable rule keys in tr_rule_configs (rule_value is the bare
|
||||
// JSON value: [3,1], 7, true).
|
||||
const (
|
||||
ruleKeyNotifyRemindDays = "notify_remind_days"
|
||||
ruleKeyNotifyLecturerMaintainDay = "notify_lecturer_maintain_days"
|
||||
ruleKeyNotifyPushEnabled = "notify_push_enabled"
|
||||
// ruleKeyNotifyWeeklyLecturer 组合键(配置中心一张卡):{"enabled":bool,"hour":int},
|
||||
// 与下面的独立键双读兼容(组合键优先)。
|
||||
ruleKeyNotifyWeeklyLecturer = "notify_weekly_lecturer"
|
||||
ruleKeyNotifyWeeklyLecturerEnabled = "notify_weekly_lecturer_enabled"
|
||||
ruleKeyNotifyWeeklyRemindHour = "notify_weekly_remind_hour"
|
||||
// ruleKeyNotifyTextTemplates [2026-11 需求] 提醒推送文案模板(配置中心可编辑,
|
||||
// 空字段回落 training_notify.go 的内置默认文案)。
|
||||
ruleKeyNotifyTextTemplates = "notify_text_templates"
|
||||
)
|
||||
|
||||
// sendingReclaimAfter bounds how long a claimed row may stay 'sending'
|
||||
// before it is considered abandoned (instance crashed mid-dispatch) and put
|
||||
// back to pending.
|
||||
const sendingReclaimAfter = 10 * time.Minute
|
||||
|
||||
// WecomPushSender sends one markdown message to the listed WeCom userids.
|
||||
// Satisfied by *wecom.ProactiveClient; an interface so tests inject fakes.
|
||||
type WecomPushSender interface {
|
||||
SendMarkdown(ctx context.Context, userIDs []string, content string) error
|
||||
}
|
||||
|
||||
// WecomPushBackend resolves per-tenant push clients and platform-user →
|
||||
// WeCom-userid bindings. Implemented by internal/im/wecompush (which owns
|
||||
// the internal/im dependency the service layer must avoid).
|
||||
type WecomPushBackend interface {
|
||||
ClientForTenant(ctx context.Context, db *gorm.DB, tenantID uint64) (WecomPushSender, error)
|
||||
TenantWecomUserIDs(ctx context.Context, db *gorm.DB, tenantID uint64, userIDs []string) (map[string]string, error)
|
||||
}
|
||||
|
||||
// SchedulerConfig holds scheduler tuning; zero fields keep defaults.
|
||||
type TrainingSchedulerConfig struct {
|
||||
// Tick is the scan interval.
|
||||
Tick time.Duration
|
||||
// RemindDaysBefore lists T-N days (relative to session start) that
|
||||
// generate a reminder, e.g. [3,1].
|
||||
RemindDaysBefore []int
|
||||
// LecturerMaintainDays is T-N days for the lecturer maintain reminder.
|
||||
LecturerMaintainDays int
|
||||
// ScanHorizonDays limits how far ahead sessions are scanned.
|
||||
ScanHorizonDays int
|
||||
// DispatchBatch caps claimed rows per tick.
|
||||
DispatchBatch int
|
||||
// MaxPushAttempts caps retries before a row is marked dead.
|
||||
MaxPushAttempts int
|
||||
}
|
||||
|
||||
// DefaultTrainingSchedulerConfig returns the production defaults
|
||||
// (T-3/T-1 reminders, maintain reminder at T-7).
|
||||
func DefaultTrainingSchedulerConfig() *TrainingSchedulerConfig {
|
||||
return &TrainingSchedulerConfig{
|
||||
Tick: 5 * time.Minute,
|
||||
RemindDaysBefore: []int{3, 1},
|
||||
LecturerMaintainDays: 7,
|
||||
ScanHorizonDays: 30,
|
||||
DispatchBatch: 100,
|
||||
MaxPushAttempts: 3,
|
||||
}
|
||||
}
|
||||
|
||||
// TrainingScheduler is the deterministic reminder engine for the training
|
||||
// module. All state lives in tr_notifications (outbox), so any instance can
|
||||
// run it; claiming is guarded by SKIP LOCKED.
|
||||
type TrainingScheduler struct {
|
||||
db *gorm.DB
|
||||
cfg *TrainingSchedulerConfig
|
||||
|
||||
// backend resolves push clients and userid bindings; overridable in tests.
|
||||
backend WecomPushBackend
|
||||
|
||||
now func() time.Time
|
||||
stopCh chan struct{}
|
||||
stopOne sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
// NewTrainingScheduler constructs the scheduler (dig-injected). The backend
|
||||
// comes from the container (wecompush.Backend).
|
||||
func NewTrainingScheduler(db *gorm.DB, backend WecomPushBackend) *TrainingScheduler {
|
||||
return &TrainingScheduler{
|
||||
db: db,
|
||||
cfg: DefaultTrainingSchedulerConfig(),
|
||||
backend: backend,
|
||||
now: time.Now,
|
||||
stopCh: make(chan struct{}),
|
||||
done: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Start launches the scan loop; it returns immediately.
|
||||
func (s *TrainingScheduler) Start(ctx context.Context) {
|
||||
go func() {
|
||||
defer close(s.done)
|
||||
ticker := time.NewTicker(s.cfg.Tick)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s.tick(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-s.stopCh:
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// StopWithin stops the loop and waits up to timeout for the current tick.
|
||||
func (s *TrainingScheduler) StopWithin(timeout time.Duration) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.stopOne.Do(func() { close(s.stopCh) })
|
||||
if !runtime.WaitFor(s.done, timeout) {
|
||||
logger.Warnf(context.Background(),
|
||||
"[TrainingScheduler] tick still running after %s; continuing shutdown", timeout)
|
||||
}
|
||||
}
|
||||
|
||||
// tick runs one scan; a panic in one step must not kill the loop.
|
||||
func (s *TrainingScheduler) tick(ctx context.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger.Errorf(ctx, "[TrainingScheduler] tick panic: %v", r)
|
||||
}
|
||||
}()
|
||||
s.reclaimStaleSending(ctx)
|
||||
if err := s.generateReminders(ctx); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] generate reminders: %v", err)
|
||||
}
|
||||
if err := s.generateWeeklyLecturerReminders(ctx); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] weekly lecturer reminders: %v", err)
|
||||
}
|
||||
if err := s.dispatchPending(ctx); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] dispatch pending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// reclaimStaleSending puts rows stuck in 'sending' (crashed instance) back
|
||||
// to pending so they are retried.
|
||||
func (s *TrainingScheduler) reclaimStaleSending(ctx context.Context) {
|
||||
err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
|
||||
Where("push_status = ? AND updated_at < ?", pushStatusSending, s.now().Add(-sendingReclaimAfter)).
|
||||
Updates(map[string]interface{}{
|
||||
"push_status": pushStatusPending,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] reclaim stale sending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 1: generate reminders
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// tenantNotifyConfig is the per-tenant reminder policy with defaults filled
|
||||
// from the scheduler config and optional tr_rule_configs overrides.
|
||||
type tenantNotifyConfig struct {
|
||||
remindDays []int
|
||||
lecturerMaintainIn int
|
||||
pushEnabled bool
|
||||
// texts 提醒推送文案模板([2026-11 需求] 配置中心「提醒推送文案」可编辑)
|
||||
texts notifyTextTemplates
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) generateReminders(ctx context.Context) error {
|
||||
now := s.now()
|
||||
horizon := now.Add(time.Duration(s.cfg.ScanHorizonDays) * 24 * time.Hour)
|
||||
|
||||
var sessions []types.TrainingCourseSession
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("deleted_at IS NULL AND status = ? AND start_at IS NOT NULL AND start_at > ? AND start_at <= ?",
|
||||
types.TrainingSessionScheduled, now, horizon).
|
||||
Find(&sessions).Error; err != nil {
|
||||
return fmt.Errorf("scan sessions: %w", err)
|
||||
}
|
||||
if len(sessions) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Group sessions by tenant so rule configs load once per tenant.
|
||||
byTenant := map[uint64][]types.TrainingCourseSession{}
|
||||
for _, sess := range sessions {
|
||||
byTenant[sess.TenantID] = append(byTenant[sess.TenantID], sess)
|
||||
}
|
||||
for tenantID, tenantSessions := range byTenant {
|
||||
cfg, err := s.loadNotifyConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] tenant %d rule config: %v", tenantID, err)
|
||||
cfg = s.defaultNotifyConfig()
|
||||
}
|
||||
if err := s.generateForTenant(ctx, tenantID, tenantSessions, cfg, now); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] tenant %d generate: %v", tenantID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) defaultNotifyConfig() tenantNotifyConfig {
|
||||
days := append([]int(nil), s.cfg.RemindDaysBefore...)
|
||||
return tenantNotifyConfig{
|
||||
remindDays: days,
|
||||
lecturerMaintainIn: s.cfg.LecturerMaintainDays,
|
||||
pushEnabled: true,
|
||||
texts: defaultNotifyTextTemplates(),
|
||||
}
|
||||
}
|
||||
|
||||
// loadNotifyConfig reads tenant overrides from tr_rule_configs; unknown or
|
||||
// invalid values fall back to the scheduler defaults.
|
||||
func (s *TrainingScheduler) loadNotifyConfig(ctx context.Context, tenantID uint64) (tenantNotifyConfig, error) {
|
||||
cfg := s.defaultNotifyConfig()
|
||||
var rules []types.TrainingRuleConfig
|
||||
err := s.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND rule_key IN ?", tenantID,
|
||||
[]string{ruleKeyNotifyRemindDays, ruleKeyNotifyLecturerMaintainDay, ruleKeyNotifyPushEnabled, ruleKeyNotifyTextTemplates}).
|
||||
Find(&rules).Error
|
||||
if err != nil {
|
||||
return cfg, err
|
||||
}
|
||||
for _, rule := range rules {
|
||||
switch rule.RuleKey {
|
||||
case ruleKeyNotifyRemindDays:
|
||||
var days []int
|
||||
if json.Unmarshal(rule.RuleValue, &days) == nil && len(days) > 0 {
|
||||
valid := days[:0]
|
||||
for _, d := range days {
|
||||
if d > 0 && d <= s.cfg.ScanHorizonDays {
|
||||
valid = append(valid, d)
|
||||
}
|
||||
}
|
||||
if len(valid) > 0 {
|
||||
cfg.remindDays = valid
|
||||
}
|
||||
}
|
||||
case ruleKeyNotifyLecturerMaintainDay:
|
||||
var days int
|
||||
if json.Unmarshal(rule.RuleValue, &days) == nil && days > 0 && days <= s.cfg.ScanHorizonDays {
|
||||
cfg.lecturerMaintainIn = days
|
||||
}
|
||||
case ruleKeyNotifyPushEnabled:
|
||||
var enabled bool
|
||||
if json.Unmarshal(rule.RuleValue, &enabled) == nil {
|
||||
cfg.pushEnabled = enabled
|
||||
}
|
||||
case ruleKeyNotifyTextTemplates:
|
||||
// [2026-11 需求] 提醒推送文案模板(空字段回落内置默认)
|
||||
cfg.texts = parseNotifyTextTemplates(rule.RuleValue)
|
||||
}
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// generateForTenant writes due reminder rows for one tenant's sessions.
|
||||
// Dedup pre-check avoids re-inserting; the partial unique index is the
|
||||
// ultimate guard (ON CONFLICT DO NOTHING tolerates concurrent generation).
|
||||
func (s *TrainingScheduler) generateForTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
sessions []types.TrainingCourseSession,
|
||||
cfg tenantNotifyConfig,
|
||||
now time.Time,
|
||||
) error {
|
||||
// Batch-load courses for titles.
|
||||
courseIDs := make([]string, 0, len(sessions))
|
||||
for _, sess := range sessions {
|
||||
courseIDs = append(courseIDs, sess.CourseID)
|
||||
}
|
||||
courses, err := s.loadCourses(ctx, tenantID, courseIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, sess := range sessions {
|
||||
if sess.StartAt == nil {
|
||||
continue
|
||||
}
|
||||
start := *sess.StartAt
|
||||
course := courses[sess.CourseID]
|
||||
|
||||
// 1) T-N day reminders. [2026-11 推学员] 学员侧开课通知收敛到
|
||||
// session_notice_student 单通道:immediate 场次由名单保存/课件上传钩子
|
||||
// 立即入队(training_notify.go),调度器不再发学员 remind_tN 重复打扰;
|
||||
// day_before 场次在 T-1 且课件就绪时在此入队(课件缺失跳过,上传课件后
|
||||
// 补推钩子兜底)。讲师 remind_tN_lecturer 授课提醒保持不变。
|
||||
for _, d := range cfg.remindDays {
|
||||
if now.Before(start.Add(-time.Duration(d) * 24 * time.Hour)) {
|
||||
continue
|
||||
}
|
||||
if sess.LecturerID != "" {
|
||||
rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID,
|
||||
types.TrainingRemindScene(d, true),
|
||||
remindTitle(cfg.texts.LecturerOpenTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
|
||||
sess.ID, cfg.pushEnabled, now)}
|
||||
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if sess.NotifyMode != types.TrainingNotifyModeDayBefore || d != 1 {
|
||||
continue
|
||||
}
|
||||
hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !hasMaterial {
|
||||
continue
|
||||
}
|
||||
targets, err := s.sessionTargets(ctx, tenantID, sess)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]*types.TrainingNotification, 0, len(targets))
|
||||
for _, uid := range targets {
|
||||
rows = append(rows, s.newReminderRow(tenantID, uid,
|
||||
types.SceneSessionNoticeStudent,
|
||||
remindTitle(cfg.texts.StudentNoticeTitle, course), remindContent(course, &sess, false, cfg.texts.LecturerOpenFooter),
|
||||
sess.ID, cfg.pushEnabled, now))
|
||||
}
|
||||
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Lecturer maintain reminder: inside the window and no materials.
|
||||
if sess.LecturerID == "" {
|
||||
continue
|
||||
}
|
||||
if now.Before(start.Add(-time.Duration(cfg.lecturerMaintainIn) * 24 * time.Hour)) {
|
||||
continue
|
||||
}
|
||||
hasMaterial, err := s.courseHasMaterial(ctx, tenantID, sess.CourseID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hasMaterial {
|
||||
continue
|
||||
}
|
||||
rows := []*types.TrainingNotification{s.newReminderRow(tenantID, sess.LecturerID,
|
||||
types.SceneRemindLecturerMaintain,
|
||||
remindTitle(cfg.texts.LecturerMaintainTitle, course), remindContent(course, &sess, true, cfg.texts.LecturerMaintainFooter),
|
||||
sess.ID, cfg.pushEnabled, now)}
|
||||
if err := s.insertNotifications(ctx, tenantID, sess.ID, rows); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sessionTargets resolves the student target user IDs (tr_enrollments →
|
||||
// org_employees.user_id) for a session.
|
||||
func (s *TrainingScheduler) sessionTargets(ctx context.Context, tenantID uint64, sess types.TrainingCourseSession) ([]string, error) {
|
||||
var enrolls []types.TrainingEnrollment
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND session_id = ? AND deleted_at IS NULL", tenantID, sess.ID).
|
||||
Find(&enrolls).Error; err != nil {
|
||||
return nil, fmt.Errorf("list enrollments: %w", err)
|
||||
}
|
||||
if len(enrolls) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
memberIDs := make([]string, 0, len(enrolls))
|
||||
for _, e := range enrolls {
|
||||
memberIDs = append(memberIDs, e.MemberID)
|
||||
}
|
||||
var members []types.OrgEmployee
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id IN ?", tenantID, memberIDs).
|
||||
Find(&members).Error; err != nil {
|
||||
return nil, fmt.Errorf("load members: %w", err)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
out := make([]string, 0, len(members))
|
||||
for _, m := range members {
|
||||
if m.UserID == "" || seen[m.UserID] {
|
||||
continue
|
||||
}
|
||||
seen[m.UserID] = true
|
||||
out = append(out, m.UserID)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) loadCourses(ctx context.Context, tenantID uint64, courseIDs []string) (map[string]types.TrainingCourse, error) {
|
||||
out := map[string]types.TrainingCourse{}
|
||||
if len(courseIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
var courses []types.TrainingCourse
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND id IN ?", tenantID, courseIDs).
|
||||
Find(&courses).Error; err != nil {
|
||||
return nil, fmt.Errorf("load courses: %w", err)
|
||||
}
|
||||
for _, c := range courses {
|
||||
out[c.ID] = c
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) courseHasMaterial(ctx context.Context, tenantID uint64, courseID string) (bool, error) {
|
||||
var count int64
|
||||
err := s.db.WithContext(ctx).Model(&types.TrainingMaterial{}).
|
||||
Where("tenant_id = ? AND course_id = ? AND deleted_at IS NULL", tenantID, courseID).
|
||||
Limit(1).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// newReminderRow builds one tr_notifications row: always visible in the
|
||||
// inapp inbox; push_status='pending' enqueues the WeCom outbox delivery.
|
||||
func (s *TrainingScheduler) newReminderRow(
|
||||
tenantID uint64, targetUserID, scene, title, content, sessionID string, push bool, now time.Time,
|
||||
) *types.TrainingNotification {
|
||||
status := ""
|
||||
if push {
|
||||
status = pushStatusPending
|
||||
}
|
||||
return &types.TrainingNotification{
|
||||
ID: trainingNewID(),
|
||||
TenantID: tenantID,
|
||||
TargetUserID: targetUserID,
|
||||
Channel: "inapp",
|
||||
Scene: scene,
|
||||
Title: title,
|
||||
Content: content,
|
||||
RefType: types.RefTypeCourseSession,
|
||||
RefID: sessionID,
|
||||
SentAt: now,
|
||||
PushStatus: status,
|
||||
}
|
||||
}
|
||||
|
||||
// insertNotifications pre-checks duplicates for this (ref_id, targets) set
|
||||
// and batch-inserts the rest; ON CONFLICT DO NOTHING is the race fallback.
|
||||
func (s *TrainingScheduler) insertNotifications(ctx context.Context, tenantID uint64, sessionID string, rows []*types.TrainingNotification) error {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
var existing []struct {
|
||||
TargetUserID string
|
||||
Scene string
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
|
||||
Select("target_user_id, scene").
|
||||
Where("tenant_id = ? AND ref_type = ? AND ref_id = ? AND deleted_at IS NULL",
|
||||
tenantID, types.RefTypeCourseSession, sessionID).
|
||||
Scan(&existing).Error; err != nil {
|
||||
return fmt.Errorf("check existing notifications: %w", err)
|
||||
}
|
||||
seen := make(map[string]bool, len(existing))
|
||||
for _, e := range existing {
|
||||
seen[e.TargetUserID+"\x00"+e.Scene] = true
|
||||
}
|
||||
fresh := rows[:0]
|
||||
for _, row := range rows {
|
||||
if seen[row.TargetUserID+"\x00"+row.Scene] {
|
||||
continue
|
||||
}
|
||||
seen[row.TargetUserID+"\x00"+row.Scene] = true
|
||||
fresh = append(fresh, row)
|
||||
}
|
||||
if len(fresh) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := s.db.WithContext(ctx).
|
||||
Clauses(clause.OnConflict{DoNothing: true}).
|
||||
Create(&fresh).Error; err != nil {
|
||||
return fmt.Errorf("insert notifications: %w", err)
|
||||
}
|
||||
logger.Infof(ctx, "[TrainingScheduler] tenant %d session %s: generated %d reminders",
|
||||
tenantID, sessionID, len(fresh))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 1.5: weekly lecturer monthly reminder (周一讲师未完成汇总)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// generateWeeklyLecturerReminders 每周一(北京时间,notify_weekly_remind_hour
|
||||
// 规则可配,默认 09:00;notify_weekly_lecturer_enabled 可整体关闭)生成一轮
|
||||
// "当月未完成讲师"汇总提醒:收件人 = 当月仍有未结束(结束时间晚于当前)场次
|
||||
// 的讲师,场次全部结束即不在集合 → 天然"完成即停推"。轮次键 ref=YYYY-MM-Wn
|
||||
// (按当月周一计数),同周内定时与手动触发共用幂等不重发。
|
||||
// 租户集合取自当月活跃场次(无场次的租户没有未完成讲师,跳过)。
|
||||
func (s *TrainingScheduler) generateWeeklyLecturerReminders(ctx context.Context) error {
|
||||
now := s.now()
|
||||
local := beijingNow(now)
|
||||
if local.Weekday() != time.Monday {
|
||||
return nil
|
||||
}
|
||||
var sessions []types.TrainingCourseSession
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("deleted_at IS NULL AND status IN ? AND year = ? AND month = ?",
|
||||
[]string{types.TrainingSessionScheduled, types.TrainingSessionOngoing},
|
||||
local.Year(), int(local.Month())).
|
||||
Find(&sessions).Error; err != nil {
|
||||
return fmt.Errorf("scan month sessions: %w", err)
|
||||
}
|
||||
if len(sessions) == 0 {
|
||||
return nil
|
||||
}
|
||||
svc := &trainingService{repo: repository.NewTrainingRepository(s.db)}
|
||||
tenants := map[uint64]bool{}
|
||||
for _, sess := range sessions {
|
||||
tenants[sess.TenantID] = true
|
||||
}
|
||||
for tenantID := range tenants {
|
||||
// weeklyLecturerDueNow:开关 + 周一 + 配置小时(北京时间)统一判断
|
||||
if !svc.weeklyLecturerDueNow(ctx, tenantID, now) {
|
||||
continue
|
||||
}
|
||||
if _, err := svc.enqueueWeeklyLecturerReminders(ctx, tenantID, now, svc.loadPushEnabled(ctx, tenantID)); err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] tenant %d weekly lecturer reminder: %v", tenantID, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 2: dispatch the WeCom outbox
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// claimedNotification mirrors the columns returned by the claim statement.
|
||||
type claimedNotification struct {
|
||||
ID string
|
||||
TenantID uint64
|
||||
TargetUserID string
|
||||
Scene string
|
||||
Title string
|
||||
Content string
|
||||
PushAttempts int
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) dispatchPending(ctx context.Context) error {
|
||||
var claimed []*claimedNotification
|
||||
err := s.db.WithContext(ctx).Raw(`
|
||||
UPDATE tr_notifications AS t
|
||||
SET push_status = ?, updated_at = CURRENT_TIMESTAMP
|
||||
FROM (
|
||||
SELECT id FROM tr_notifications
|
||||
WHERE push_status = ? AND deleted_at IS NULL
|
||||
ORDER BY created_at, id
|
||||
LIMIT ?
|
||||
FOR UPDATE SKIP LOCKED
|
||||
) AS c
|
||||
WHERE t.id = c.id
|
||||
RETURNING t.id, t.tenant_id, t.target_user_id, t.scene, t.title, t.content, t.push_attempts`,
|
||||
pushStatusSending, pushStatusPending, s.cfg.DispatchBatch).
|
||||
Scan(&claimed).Error
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim pending notifications: %w", err)
|
||||
}
|
||||
if len(claimed) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
byTenant := map[uint64][]*claimedNotification{}
|
||||
for _, row := range claimed {
|
||||
byTenant[row.TenantID] = append(byTenant[row.TenantID], row)
|
||||
}
|
||||
for tenantID, rows := range byTenant {
|
||||
s.dispatchTenant(ctx, tenantID, rows)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *TrainingScheduler) dispatchTenant(ctx context.Context, tenantID uint64, rows []*claimedNotification) {
|
||||
client, clientErr := s.backend.ClientForTenant(ctx, s.db, tenantID)
|
||||
if clientErr != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] tenant %d wecom client: %v", tenantID, clientErr)
|
||||
}
|
||||
targets := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
targets = append(targets, row.TargetUserID)
|
||||
}
|
||||
mapping := map[string]string{}
|
||||
if client != nil {
|
||||
var err error
|
||||
mapping, err = s.backend.TenantWecomUserIDs(ctx, s.db, tenantID, targets)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] tenant %d wecom userid lookup: %v", tenantID, err)
|
||||
mapping = map[string]string{}
|
||||
}
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
switch {
|
||||
case clientErr != nil:
|
||||
s.finishPush(ctx, row, pushStatusSkipped, nil, clientErr.Error())
|
||||
case mapping[row.TargetUserID] == "":
|
||||
s.finishPush(ctx, row, pushStatusSkipped, nil, "缺少企微 userid 绑定")
|
||||
default:
|
||||
err := client.SendMarkdown(ctx, []string{mapping[row.TargetUserID]}, row.Content)
|
||||
if err == nil {
|
||||
s.finishPush(ctx, row, pushStatusSent, ptrTime(s.now()), "")
|
||||
continue
|
||||
}
|
||||
logger.Warnf(ctx, "[TrainingScheduler] push notification %s to tenant %d user %s: %v",
|
||||
row.ID, tenantID, row.TargetUserID, err)
|
||||
if row.PushAttempts+1 >= s.cfg.MaxPushAttempts {
|
||||
s.finishPush(ctx, row, pushStatusDead, nil, err.Error())
|
||||
} else {
|
||||
s.finishPush(ctx, row, pushStatusPending, nil, err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// finishPush records the delivery outcome of one outbox row. A retry keeps
|
||||
// push_status='pending' and bumps attempts; pushed_at is only set on success.
|
||||
func (s *TrainingScheduler) finishPush(ctx context.Context, row *claimedNotification, status string, pushedAt *time.Time, pushErr string) {
|
||||
updates := map[string]interface{}{
|
||||
"push_status": status,
|
||||
"push_error": clipRunes(pushErr, 500),
|
||||
"updated_at": time.Now(),
|
||||
}
|
||||
if status == pushStatusPending {
|
||||
updates["push_attempts"] = row.PushAttempts + 1
|
||||
} else {
|
||||
updates["push_attempts"] = row.PushAttempts
|
||||
}
|
||||
if pushedAt != nil {
|
||||
updates["pushed_at"] = *pushedAt
|
||||
}
|
||||
if err := s.db.WithContext(ctx).Model(&types.TrainingNotification{}).
|
||||
Where("id = ?", row.ID).Updates(updates).Error; err != nil {
|
||||
logger.Warnf(ctx, "[TrainingScheduler] record push result %s: %v", row.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Test push (plumbing via the injected backend)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// PushTestNotification sends a direct WeCom test message so operators can
|
||||
// verify credentials and the userid binding without waiting for a schedule.
|
||||
func (s *TrainingScheduler) PushTestNotification(ctx context.Context, tenantID uint64, operatorUserID, targetUserID, content string) error {
|
||||
client, err := s.backend.ClientForTenant(ctx, s.db, tenantID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mapping, err := s.backend.TenantWecomUserIDs(ctx, s.db, tenantID, []string{targetUserID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
wecomUserID, ok := mapping[targetUserID]
|
||||
if !ok {
|
||||
return errors.New("该用户未绑定企微 userid(请在组织中心员工档案维护 wecom_userid)")
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
content = fmt.Sprintf("**【培训平台推送测试】**\n操作人:%s\n时间:%s\n收到本条消息即企微推送链路正常。",
|
||||
operatorUserID, s.now().Format("2006-01-02 15:04"))
|
||||
}
|
||||
return client.SendMarkdown(ctx, []string{wecomUserID}, content)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Content templates
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func remindTitle(prefix string, course types.TrainingCourse) string {
|
||||
if course.Name == "" {
|
||||
return prefix
|
||||
}
|
||||
return fmt.Sprintf("%s:%s", prefix, course.Name)
|
||||
}
|
||||
|
||||
// remindContent renders the WeCom markdown body of a session reminder; the
|
||||
// maintain variant asks the lecturer to upload missing materials.
|
||||
// [2026-11 需求] 结尾文案 footer 由配置中心「提醒推送文案」提供(缺省为内置默认)。
|
||||
func remindContent(course types.TrainingCourse, sess *types.TrainingCourseSession, maintain bool, footer string) string {
|
||||
var b strings.Builder
|
||||
if maintain {
|
||||
b.WriteString("**【课程维护提醒】**\n")
|
||||
} else {
|
||||
b.WriteString("**【培训开课提醒】**\n")
|
||||
}
|
||||
if course.Name != "" {
|
||||
b.WriteString(fmt.Sprintf("> 课程:%s\n", course.Name))
|
||||
}
|
||||
if sess.StartAt != nil {
|
||||
b.WriteString(fmt.Sprintf("> 开课时间:%s\n", sess.StartAt.Local().Format("2006-01-02 15:04")))
|
||||
}
|
||||
switch {
|
||||
case sess.OnlineURL != "":
|
||||
b.WriteString(fmt.Sprintf("> 参与方式:[线上课堂](%s)\n", sess.OnlineURL))
|
||||
case sess.Location != "":
|
||||
b.WriteString(fmt.Sprintf("> 地点:%s\n", sess.Location))
|
||||
}
|
||||
footer = strings.TrimSpace(footer)
|
||||
if footer == "" {
|
||||
if maintain {
|
||||
footer = defaultLecturerMaintainFooter
|
||||
} else {
|
||||
footer = defaultLecturerOpenFooter
|
||||
}
|
||||
}
|
||||
b.WriteString("\n" + footer)
|
||||
return b.String()
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// fakeWecomBackend serves a fake sender plus a userid mapping to the
|
||||
// scheduler under test.
|
||||
type fakeWecomBackend struct {
|
||||
sender *fakePushSender
|
||||
clientErr error
|
||||
mapping map[string]string
|
||||
lookupErr error
|
||||
}
|
||||
|
||||
func (f *fakeWecomBackend) ClientForTenant(context.Context, *gorm.DB, uint64) (WecomPushSender, error) {
|
||||
if f.clientErr != nil {
|
||||
return nil, f.clientErr
|
||||
}
|
||||
return f.sender, nil
|
||||
}
|
||||
|
||||
func (f *fakeWecomBackend) TenantWecomUserIDs(context.Context, *gorm.DB, uint64, []string) (map[string]string, error) {
|
||||
if f.lookupErr != nil {
|
||||
return nil, f.lookupErr
|
||||
}
|
||||
return f.mapping, nil
|
||||
}
|
||||
|
||||
// fakePushSender records SendMarkdown calls for dispatcher assertions.
|
||||
type fakePushSender struct {
|
||||
sent [][]string
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakePushSender) SendMarkdown(_ context.Context, userIDs []string, _ string) error {
|
||||
if f.err != nil {
|
||||
return f.err
|
||||
}
|
||||
f.sent = append(f.sent, userIDs)
|
||||
return nil
|
||||
}
|
||||
|
||||
type trainingPushFixture struct {
|
||||
db *gorm.DB
|
||||
sched *TrainingScheduler
|
||||
now time.Time
|
||||
backend *fakeWecomBackend
|
||||
tenantID uint64
|
||||
}
|
||||
|
||||
func newTrainingPushFixture(t *testing.T) *trainingPushFixture {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(
|
||||
sqlite.Open(filepath.Join(t.TempDir(), "training_push.db")+"?_busy_timeout=5000&_journal_mode=WAL"),
|
||||
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent)},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
raw, err := db.DB()
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = raw.Close() })
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&types.TrainingCourseSession{}, &types.TrainingCourse{}, &types.TrainingEnrollment{},
|
||||
&types.OrgEmployee{}, &types.TrainingNotification{}, &types.TrainingMaterial{},
|
||||
&types.TrainingRuleConfig{},
|
||||
))
|
||||
|
||||
const tenantID = uint64(42)
|
||||
now := time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC)
|
||||
backend := &fakeWecomBackend{sender: &fakePushSender{}, mapping: map[string]string{}}
|
||||
sched := NewTrainingScheduler(db, backend)
|
||||
sched.now = func() time.Time { return now }
|
||||
return &trainingPushFixture{db: db, sched: sched, now: now, backend: backend, tenantID: tenantID}
|
||||
}
|
||||
|
||||
// seedSession inserts a course + scheduled session; materials controls
|
||||
// whether the course already has one material row. notifyMode 传空即
|
||||
// immediate(默认,调度器不再生成学员 remind_tN,学员通知由保存名单钩子入队)。
|
||||
func (f *trainingPushFixture) seedSession(t *testing.T, startOffset time.Duration, materials bool, lecturerID string) types.TrainingCourseSession {
|
||||
t.Helper()
|
||||
course := types.TrainingCourse{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, Name: "安全生产培训", Status: "published",
|
||||
}
|
||||
require.NoError(t, f.db.Create(&course).Error)
|
||||
if materials {
|
||||
require.NoError(t, f.db.Create(&types.TrainingMaterial{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, CourseID: course.ID, Name: "课件.pdf",
|
||||
}).Error)
|
||||
}
|
||||
start := f.now.Add(startOffset)
|
||||
sess := types.TrainingCourseSession{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, CourseID: course.ID,
|
||||
StartAt: &start, Location: "三楼会议室", LecturerID: lecturerID,
|
||||
Status: types.TrainingSessionScheduled,
|
||||
}
|
||||
require.NoError(t, f.db.Create(&sess).Error)
|
||||
return sess
|
||||
}
|
||||
|
||||
// setSessionNotifyMode 直接改写场次通知方式(day_before 用例用)。
|
||||
func (f *trainingPushFixture) setSessionNotifyMode(t *testing.T, sessionID, mode string) {
|
||||
t.Helper()
|
||||
require.NoError(t, f.db.Model(&types.TrainingCourseSession{}).
|
||||
Where("id = ?", sessionID).Update("notify_mode", mode).Error)
|
||||
}
|
||||
|
||||
// seedEnrolledStudent wires enrollment → org_employee for userID.
|
||||
func (f *trainingPushFixture) seedEnrolledStudent(t *testing.T, sessionID, userID, wecomUserid string) {
|
||||
t.Helper()
|
||||
member := types.OrgEmployee{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, UserID: userID, WecomUserid: wecomUserid,
|
||||
}
|
||||
require.NoError(t, f.db.Create(&member).Error)
|
||||
require.NoError(t, f.db.Create(&types.TrainingEnrollment{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, SessionID: sessionID, MemberID: member.ID,
|
||||
}).Error)
|
||||
}
|
||||
|
||||
func (f *trainingPushFixture) notificationScenes(t *testing.T) map[string]int {
|
||||
t.Helper()
|
||||
var rows []*types.TrainingNotification
|
||||
require.NoError(t, f.db.Find(&rows).Error)
|
||||
out := map[string]int{}
|
||||
for _, r := range rows {
|
||||
out[r.TargetUserID+"\x00"+r.Scene]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestGenerateRemindersIdempotent(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
// [2026-11 推学员] immediate 场次:调度器只发讲师 remind_tN;学员开课通知
|
||||
// 由保存名单钩子入队(session_notice_student),调度器不再重复发学员 remind_tN。
|
||||
sess := f.seedSession(t, 72*time.Hour, true, "lecturer-1") // T-3 due, has material
|
||||
f.seedEnrolledStudent(t, sess.ID, "user-1", "wecom_u1")
|
||||
|
||||
// Two consecutive ticks must not duplicate rows (dedup index semantics).
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
|
||||
scenes := f.notificationScenes(t)
|
||||
require.NotContains(t, scenes, "user-1\x00"+types.TrainingRemindScene(3, false),
|
||||
"student remind_tN removed: immediate sessions enqueue session_notice_student on roster save")
|
||||
require.Equal(t, 1, scenes["lecturer-1\x00"+types.TrainingRemindScene(3, true)], "lecturer T-3 reminder once")
|
||||
require.NotContains(t, scenes, "user-1\x00"+types.TrainingRemindScene(1, false), "T-1 not due yet")
|
||||
|
||||
// Lecturer row enters the WeCom outbox.
|
||||
var row types.TrainingNotification
|
||||
require.NoError(t, f.db.Where("scene = ?", types.TrainingRemindScene(3, true)).First(&row).Error)
|
||||
require.Equal(t, pushStatusPending, row.PushStatus)
|
||||
require.Equal(t, types.RefTypeCourseSession, row.RefType)
|
||||
require.Equal(t, sess.ID, row.RefID)
|
||||
require.Equal(t, "inapp", row.Channel)
|
||||
}
|
||||
|
||||
// TestGenerateDayBeforeStudentNotice day_before 场次:T-1 且课件就绪时调度器
|
||||
// 入队学员开课通知(session_notice_student);课件缺失时跳过,改期重排后仍幂等。
|
||||
func TestGenerateDayBeforeStudentNotice(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
sess := f.seedSession(t, 24*time.Hour, true, "lecturer-2") // T-1 due, has material
|
||||
f.setSessionNotifyMode(t, sess.ID, types.TrainingNotifyModeDayBefore)
|
||||
f.seedEnrolledStudent(t, sess.ID, "user-2", "wecom_u2")
|
||||
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
|
||||
scenes := f.notificationScenes(t)
|
||||
require.Equal(t, 1, scenes["user-2\x00"+types.SceneSessionNoticeStudent],
|
||||
"day_before student notice once at T-1")
|
||||
require.NotContains(t, scenes, "user-2\x00"+types.TrainingRemindScene(1, false),
|
||||
"student notice uses the single session_notice_student scene")
|
||||
|
||||
// 无课件的 day_before 场次:T-1 跳过,等上传课件后由 service 补推钩子兜底。
|
||||
bare := f.seedSession(t, 24*time.Hour, false, "lecturer-3")
|
||||
f.setSessionNotifyMode(t, bare.ID, types.TrainingNotifyModeDayBefore)
|
||||
f.seedEnrolledStudent(t, bare.ID, "user-3", "wecom_u3")
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
scenes = f.notificationScenes(t)
|
||||
require.NotContains(t, scenes, "user-3\x00"+types.SceneSessionNoticeStudent,
|
||||
"missing courseware gates the day_before student notice")
|
||||
}
|
||||
|
||||
func TestGenerateMaintainReminderOnlyWithoutMaterials(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
// T+5d: outside T-3/T-1 remind windows, inside the 7-day maintain window.
|
||||
f.seedSession(t, 5*24*time.Hour, false, "lecturer-1")
|
||||
f.seedSession(t, 6*24*time.Hour, true, "lecturer-2")
|
||||
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
|
||||
scenes := f.notificationScenes(t)
|
||||
require.Equal(t, 1, scenes["lecturer-1\x00"+types.SceneRemindLecturerMaintain],
|
||||
"maintain reminder when no materials")
|
||||
require.NotContains(t, scenes, "lecturer-2\x00"+types.SceneRemindLecturerMaintain,
|
||||
"no maintain reminder when materials exist")
|
||||
require.NotContains(t, scenes, "lecturer-1\x00"+types.TrainingRemindScene(3, true),
|
||||
"T-3 not due for the 5d-out session")
|
||||
}
|
||||
|
||||
func TestGeneratePushDisabledKeepsOutboxEmpty(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
sess := f.seedSession(t, 72*time.Hour, true, "lecturer-1")
|
||||
f.seedEnrolledStudent(t, sess.ID, "user-1", "wecom_u1")
|
||||
require.NoError(t, f.db.Create(&types.TrainingRuleConfig{
|
||||
ID: trainingNewID(), TenantID: f.tenantID, RuleKey: ruleKeyNotifyPushEnabled, RuleValue: types.JSON("false"),
|
||||
}).Error)
|
||||
|
||||
require.NoError(t, f.sched.generateReminders(context.Background()))
|
||||
|
||||
var rows []*types.TrainingNotification
|
||||
require.NoError(t, f.db.Find(&rows).Error)
|
||||
require.NotEmpty(t, rows, "inapp rows still generated")
|
||||
for _, r := range rows {
|
||||
require.Empty(t, r.PushStatus, "push disabled → no outbox entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDispatchTenantOutcomes(t *testing.T) {
|
||||
t.Run("sent on success", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-1", Scene: "s", Content: "c", PushStatus: pushStatusSending}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID,
|
||||
[]*claimedNotification{{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1", Content: "c"}})
|
||||
|
||||
var got types.TrainingNotification
|
||||
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
|
||||
require.Equal(t, pushStatusSent, got.PushStatus)
|
||||
require.NotNil(t, got.PushedAt)
|
||||
require.Equal(t, [][]string{{"wecom_u1"}}, f.backend.sender.sent)
|
||||
})
|
||||
|
||||
t.Run("retry then dead at max attempts", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
f.backend.sender.err = errors.New("wecom api error: code=1 msg=invalid userid")
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-1", Scene: "s", PushStatus: pushStatusSending, PushAttempts: 0}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
claim := &claimedNotification{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1"}
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID, []*claimedNotification{claim})
|
||||
var got types.TrainingNotification
|
||||
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
|
||||
require.Equal(t, pushStatusPending, got.PushStatus, "attempt 1 → back to pending")
|
||||
require.Equal(t, 1, got.PushAttempts)
|
||||
|
||||
// Final allowed attempt fails → dead.
|
||||
got.PushAttempts = f.sched.cfg.MaxPushAttempts - 1
|
||||
got.PushStatus = pushStatusSending
|
||||
require.NoError(t, f.db.Save(&got).Error)
|
||||
claim.PushAttempts = got.PushAttempts
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID, []*claimedNotification{claim})
|
||||
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
|
||||
require.Equal(t, pushStatusDead, got.PushStatus)
|
||||
require.NotEmpty(t, got.PushError)
|
||||
})
|
||||
|
||||
t.Run("skipped without userid binding", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
// user-2 has no mapping entry.
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-2", Scene: "s", PushStatus: pushStatusSending}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID,
|
||||
[]*claimedNotification{{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-2"}})
|
||||
|
||||
var got types.TrainingNotification
|
||||
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
|
||||
require.Equal(t, pushStatusSkipped, got.PushStatus)
|
||||
require.Contains(t, got.PushError, "企微")
|
||||
})
|
||||
|
||||
t.Run("skipped when client unavailable", func(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
f.backend.clientErr = errors.New("未配置企微自建应用渠道")
|
||||
row := &types.TrainingNotification{ID: trainingNewID(), TenantID: f.tenantID,
|
||||
TargetUserID: "user-1", Scene: "s", PushStatus: pushStatusSending}
|
||||
require.NoError(t, f.db.Create(row).Error)
|
||||
|
||||
f.sched.dispatchTenant(context.Background(), f.tenantID,
|
||||
[]*claimedNotification{{ID: row.ID, TenantID: f.tenantID, TargetUserID: "user-1"}})
|
||||
|
||||
var got types.TrainingNotification
|
||||
require.NoError(t, f.db.Where("id = ?", row.ID).First(&got).Error)
|
||||
require.Equal(t, pushStatusSkipped, got.PushStatus)
|
||||
require.Contains(t, got.PushError, "未配置企微自建应用渠道")
|
||||
})
|
||||
}
|
||||
|
||||
func TestPushTestNotification(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
f.backend.mapping["user-1"] = "wecom_u1"
|
||||
|
||||
require.NoError(t, f.sched.PushTestNotification(context.Background(), f.tenantID, "op-1", "user-1", "hello"))
|
||||
require.Equal(t, [][]string{{"wecom_u1"}}, f.backend.sender.sent)
|
||||
|
||||
err := f.sched.PushTestNotification(context.Background(), f.tenantID, "op-1", "user-missing", "")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "wecom_userid")
|
||||
}
|
||||
|
||||
func TestRemindContent(t *testing.T) {
|
||||
f := newTrainingPushFixture(t)
|
||||
sess := f.seedSession(t, 72*time.Hour, false, "lecturer-1")
|
||||
courses, err := f.sched.loadCourses(context.Background(), f.tenantID, []string{sess.CourseID})
|
||||
require.NoError(t, err)
|
||||
course := courses[sess.CourseID]
|
||||
|
||||
student := remindContent(course, &sess, false, defaultLecturerOpenFooter)
|
||||
require.Contains(t, student, "安全生产培训")
|
||||
require.Contains(t, student, sess.StartAt.Local().Format("2006-01-02 15:04"))
|
||||
require.Contains(t, student, "三楼会议室")
|
||||
|
||||
maintain := remindContent(course, &sess, true, defaultLecturerMaintainFooter)
|
||||
require.Contains(t, maintain, "课程维护提醒")
|
||||
require.True(t, strings.Contains(maintain, "课件"), "maintain copy mentions materials")
|
||||
}
|
||||
Reference in new issue
Block a user