Files
ai_academy/internal/application/service/training_scheduler.go
T
runny 4e25fce9aa feat(training): 企业培训迭代:推送深链接与签名下载、课程管理修复与收集模板调整
推送域(000155):
- 广播通知支持 link_url:demand_collect 场景自动签发教育训练需求表模板
  匿名下载直链(HMAC token,20 天有效,免登录路由),企微消息尾部拼
  「下载模板 + 查看更多详情」链接;站内文本保持纯文本不受影响
- 配置中心新增「推送链接基址」(notify_link_base_url,多入口/内外网部署固定
  权威地址,留空跟随推送人访问地址)与「年培训计划收集推送文案」
  (demand_collect_*,{year} 渲染收集年度);空标题/内容按模板回落渲染
- 迁移 000155:tr_training_notifications 增 link_url/link_token 列

课程管理:
- 修复点【发布/下线】报「不支持的操作」:动作取值兼容字面量路由(FullPath
  末段)与 :action 通配两种注册形态
- 列表新增「创建人」列:creator_id 联查 users 带出姓名,导出 Excel 同步;
  新增课程「所属部门」默认当前登录用户所在部门
- 导入加固:表头归一化 + 别名模糊匹配(兼容内置模板/旧口径/自定义模板变体);
  导入与新增行支持按部门名兜底解析为 id(前端名册未命中时传 owner_dept_name)

年培训计划:
- 需求列表新增「创建人/创建时间」列(submitter_id 联查 users 带出姓名)
- 收集模板调整:下载时动态删除「培训费用(RMB)」列(旧版自定义模板同步归一,
  右侧列/合并/下拉随删列平移);备注右侧追加「调研维度/培训策划要求」说明列
  (合并至数据区末行,自动换行带边框,已带说明的自定义模板不覆盖)

开发工具:
- air 热重载适配 Windows:构建收敛到 scripts/air_build.sh(规避 air 经
  PowerShell 执行不支持 bash 命令替换),产物改 .exe 后缀;CGO_CFLAGS 取
  持久化值并集追加,不覆盖 go env -w 的头文件包含路径
2026-11-19 17:10:12 +08:00

767 lines
27 KiB
Go

// 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"
// ruleKeyNotifyLinkBaseURL [2026-11 需求] 企微消息内深链接的对外基址覆盖
// (bare string,如 https://aido.example.com):多入口/内外网部署时固定链接
// 指向权威域名,优先于推送人浏览器 origin;空 = 用推送人 origin。
ruleKeyNotifyLinkBaseURL = "notify_link_base_url"
)
// 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
LinkURL string
LinkToken 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.link_url, t.link_token, 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]}, wecomDispatchContent(row))
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()
}