推送域(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 的头文件包含路径
672 lines
26 KiB
Go
672 lines
26 KiB
Go
// 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"
|
|
"academy/internal/utils"
|
|
)
|
|
|
|
// 周一讲师汇总提醒的规则键(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"`
|
|
// 年培训计划收集推送(scene=demand_collect):广播空标题/内容回落渲染
|
|
DemandCollectTitle string `json:"demand_collect_title"`
|
|
DemandCollectContent string `json:"demand_collect_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} 场培训未结束,请与人事约定培训时间并于月内完成课件、签到与评价。"
|
|
// 年培训计划收集推送默认文案(与前端收集弹窗历史硬编码逐字一致;{year} 渲染收集年度)
|
|
defaultDemandCollectTitle = "【培训需求收集】{year}年度培训计划收集"
|
|
defaultDemandCollectContent = "请各部门于 {year} 年 1 月 31 日前提报 {year} 年度培训需求:可点击消息中的「教育训练需求表模板」链接直接下载批量填写后导入,或登录 AIDO → 企业培训 → 培训计划 → 年度需求收集在线逐条提报。"
|
|
)
|
|
|
|
func defaultNotifyTextTemplates() notifyTextTemplates {
|
|
return notifyTextTemplates{
|
|
StudentNoticeTitle: defaultStudentNoticeTitle,
|
|
StudentNoticeContent: defaultStudentNoticeContent,
|
|
LecturerOpenTitle: defaultLecturerOpenTitle,
|
|
LecturerOpenFooter: defaultLecturerOpenFooter,
|
|
LecturerMaintainTitle: defaultLecturerMaintainTitle,
|
|
LecturerMaintainFooter: defaultLecturerMaintainFooter,
|
|
WeeklyTitle: defaultWeeklyTitle,
|
|
WeeklyContent: defaultWeeklyContent,
|
|
DemandCollectTitle: defaultDemandCollectTitle,
|
|
DemandCollectContent: defaultDemandCollectContent,
|
|
}
|
|
}
|
|
|
|
// 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)
|
|
fill(&t.DemandCollectTitle, saved.DemandCollectTitle)
|
|
fill(&t.DemandCollectContent, saved.DemandCollectContent)
|
|
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))
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// demand_collect 年培训计划收集推送(2026-11 需求:文案可配 + 模板下载/详情入口)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// demandCollectYear 从广播 ref_id 前缀解析收集年度("2027-<纳秒>" → 2027,
|
|
// 前端收集弹窗恒传下一年度);无合法年份前缀时回退北京时间下一年。
|
|
func demandCollectYear(refID string, now time.Time) int {
|
|
if idx := strings.IndexByte(refID, '-'); idx > 0 {
|
|
refID = refID[:idx]
|
|
}
|
|
if year, err := strconv.Atoi(refID); err == nil && year >= 2000 && year <= 2999 {
|
|
return year
|
|
}
|
|
return beijingNow(now).Year() + 1
|
|
}
|
|
|
|
// demandCollectPlanPath 年培训计划页(前端铃铛 ref_type=plan 同款跳转目标)。
|
|
const demandCollectPlanPath = "/platform/training/plan"
|
|
|
|
// wecomDispatchContent 企微投递正文 = 站内 content + 场景尾部链接。
|
|
// demand_collect 且行内带 link_url 时追加两行 markdown 链接:
|
|
//
|
|
// 下载教育训练需求表模板(签名匿名直链,20 天有效;无 token 时省略)
|
|
// 查看更多详情>>(进入企业培训系统年培训计划页)
|
|
//
|
|
// 其余场景原样返回(提醒类场景的 markdown 由生成侧 remindContent 拼好)。
|
|
func wecomDispatchContent(row *claimedNotification) string {
|
|
if row.Scene != types.SceneDemandCollect || row.LinkURL == "" {
|
|
return row.Content
|
|
}
|
|
var b strings.Builder
|
|
b.WriteString(strings.TrimRight(row.Content, "\n"))
|
|
if row.LinkToken != "" {
|
|
b.WriteString("\n\n[下载教育训练需求表模板](")
|
|
b.WriteString(row.LinkURL)
|
|
b.WriteString(utils.TrainingTemplateSignedFilePath)
|
|
b.WriteString("?token=")
|
|
b.WriteString(row.LinkToken)
|
|
b.WriteString(")")
|
|
}
|
|
b.WriteString("\n[查看更多详情>>](")
|
|
b.WriteString(row.LinkURL)
|
|
b.WriteString(demandCollectPlanPath)
|
|
b.WriteString(")")
|
|
return b.String()
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 推送记录(管理台逐人明细)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// 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
|
|
}
|