[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 全部通过。
258 lines
10 KiB
Go
258 lines
10 KiB
Go
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)
|
|
}
|