// 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" "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 } // --------------------------------------------------------------------------- // 学员开课通知(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 组装学员开课通知文案(时间/地点或线上链接/讲师)。 func (s *trainingService) sessionNoticeText(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession) (string, string) { courseName := sessionCourseTitle(ctx, s, tenantID, session) title := "培训开课通知" place := session.Location if session.OnlineURL != "" { place = "线上会议(链接见课程页)" } lecturerName := "" if lecturer, err := s.repo.GetMember(ctx, tenantID, session.LecturerID); err == nil && lecturer != nil { lecturerName = lecturer.UserName } content := fmt.Sprintf("您被点名参加「%s」培训:%s,%s。请准时参加。", courseName, sessionTimeText(session), place) if lecturerName != "" { content = fmt.Sprintf("您被点名参加「%s」培训:%s,%s,讲师:%s。请准时参加。", courseName, sessionTimeText(session), place, 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 } title := fmt.Sprintf("%d年%d月教育训练(第%d周提醒)", local.Year(), int(local.Month()), weekOfMonth(local)) weekStart := local.AddDate(0, 0, -int(local.Weekday()+6)%7) weekEnd := weekStart.AddDate(0, 0, 6) 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 content := fmt.Sprintf( "%d 月已进入第 %d 周(%s 至 %s),您本月仍有 %d 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。", int(local.Month()), weekOfMonth(local), weekStart.Format("01-02"), weekEnd.Format("01-02"), count) 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 }