[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 全部通过。
335 lines
13 KiB
Go
335 lines
13 KiB
Go
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")
|
|
}
|