deploy-hxtesting / build-and-deploy (push) Successful in 1m14s
规则:1.签到要校验是否为培训当天签到,如果不是当天扫码签到则进行友好提示;2. 签到需提供员工工号及随机时间戳(超过签到二维码有效期后需重新扫码签到);3.签到二维码每5分钟自动更新一次(更新后之前扫码签到自动作废需重新扫码); 补充说明:1.签到页面需展示该签到课程相关信息;2.展示签到倒计时还有多久过期,过期后需重新扫码进行优化提示;3.签到后提示签到成功!自动登录进入平台系统并进入该课程详情页面
263 lines
11 KiB
Go
263 lines
11 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, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: channel})
|
|
}
|
|
// 复用 Checkin 的规则引擎,以目标成员的 user_id 走完整校验。
|
|
// 代录不携工号/nonce:工号严格名单硬拒与防重放仅约束学员扫码链路。
|
|
record, err := s.Checkin(ctx, tenantID, target.UserID, &types.CheckinInput{Token: token, Lat: lat, Lng: lng, Channel: "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())
|
|
// [2026-11 需求] 课程分类默认字典(配置中心「课程分类」卡;课程管理
|
|
// 筛选/表单下拉选项,缺失时前端有同值兜底)
|
|
categoryDictRaw, _ := json.Marshal(map[string]any{"categories": types.DefaultCourseCategories()})
|
|
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),
|
|
types.RuleKeyCourseCategoryDict: string(categoryDictRaw),
|
|
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)
|
|
}
|