package service import ( "bytes" "context" "encoding/json" "fmt" "io" "math" "math/rand" "mime/multipart" "path" "regexp" "sort" "strings" "time" "academy/internal/errors" "academy/internal/types" "academy/internal/types/interfaces" "github.com/xuri/excelize/v2" ) // --------------------------------------------------------------------------- // 考试域:题库导入 → AI 组卷(确定性抽题)→ 在线判分 → 错题归集 // --------------------------------------------------------------------------- // ListQuestionBanks returns a page of banks. func (s *trainingService) ListQuestionBanks(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingQuestionBank, int64, error) { return s.repo.ListQuestionBanks(ctx, tenantID, q) } // ImportQuestionBank saves a bank with its questions and refreshes the count. func (s *trainingService) ImportQuestionBank(ctx context.Context, tenantID uint64, bank *types.TrainingQuestionBank, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) { if bank.Name == "" { return nil, errors.NewBadRequestError("题库名称不能为空") } if len(questions) == 0 { return nil, errors.NewBadRequestError("题目为空") } bank.ID = trainingNewID() bank.TenantID = tenantID bank.CreatorID = updaterID bank.QuestionCount = len(questions) // 试题库编号(QB-####,导入/AI 生成统一在此生成,000153)。 bank.Code = s.nextQuestionBankCode(ctx, tenantID) if err := s.repo.CreateQuestionBank(ctx, bank); err != nil { return nil, err } for i, q := range questions { q.ID = trainingNewID() q.TenantID = tenantID q.BankID = bank.ID q.SeqNo = i + 1 if q.Type == "" { q.Type = types.TrainingQuestionSingle } } if err := s.repo.BatchCreateQuestions(ctx, questions); err != nil { return nil, err } return bank, nil } // ImportQuestionBankExcel parses question Excel in either layout: // // 1. 简表版(单工作表,按列位置): 题型 | 题干 | 选项(JSON数组或A|B|C分隔) | 答案 | 分值 | 难度 | 知识点 | 解析 // 2. 题库导入版模板(docs/moban/部门培训课程试题(题库导入版)模板.xlsx): 多工作表 // (单选题/多选题/判断题,题型按工作表名识别),表头「题目:|课程名称|难度:|正确答案|答案A..答案L」, // 选项按列展开;难度支持高/中/低文本,考核点(知识点)/解析/分值列可选。 // // 模板中的「课程名称」列仅作对照展示,题库与课程的关联以导入弹窗选择的课程为准。 // 两种格式均合并解析全部工作表;入库后把原始 Excel 自动同步进系统默认 // 「企业培训(题库)」知识库(fail-open),使题库内容支持 AI 对话问答。 func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID, libraryCourseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error) { if fh == nil { return nil, errors.NewBadRequestError("缺少上传文件") } src, err := fh.Open() if err != nil { return nil, errors.NewBadRequestError("文件读取失败").WithDetails(err.Error()) } data, readErr := io.ReadAll(src) _ = src.Close() if readErr != nil { return nil, errors.NewBadRequestError("文件读取失败").WithDetails(readErr.Error()) } questions, err := s.parseQuestionBankExcel(ctx, tenantID, data) if err != nil { return nil, err } // 同名重导入即替换:清掉旧题库的题目与缓存试卷(坏数据/旧 ONLINE 卷一并失效), // 调用方未指定归属课程/课程管理条目时继承旧题库的关联。 oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name) if err != nil { return nil, err } if courseID == "" { courseID = oldCourseID } if libraryCourseID == "" { libraryCourseID = oldLibraryCourseID } bank := &types.TrainingQuestionBank{Name: name, DeptID: deptID, CourseID: courseID, LibraryCourseID: libraryCourseID} // 原始 Excel 同步进「企业培训(题库)」知识库(失败不阻断导入),回填 knowledge_id。 bank.KnowledgeID = s.syncExcelToQuestionBankKB(ctx, fh, name) return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID) } // parseQuestionBankExcel 解析 Excel 题目数据(题库导入版模板/简表两种布局)。 func (s *trainingService) parseQuestionBankExcel(ctx context.Context, tenantID uint64, data []byte) ([]*types.TrainingQuestion, error) { f, err := excelize.OpenReader(bytes.NewReader(data)) if err != nil { return nil, errors.NewBadRequestError("Excel 文件解析失败").WithDetails(err.Error()) } questions := make([]*types.TrainingQuestion, 0) totalRows := 0 for _, sheet := range f.GetSheetList() { rows, err := f.GetRows(sheet) if err != nil || len(rows) == 0 { continue } totalRows += len(rows) if headerIdx, col, ok := detectTemplateQuestionHeader(rows); ok { // 题库导入版模板:题目行之前的说明/表头跳过,题型取工作表名(兼容同表分节)。 questions = append(questions, parseTemplateQuestionSheet(rows[headerIdx+1:], col, questionTypeFromSheetName(sheet))...) continue } questions = append(questions, parseLegacyQuestionSheet(rows)...) } if totalRows == 0 { return nil, errors.NewBadRequestError("Excel 内容为空") } if len(questions) == 0 { return nil, errors.NewBadRequestError("未解析到有效题目(需含题干与答案)") } return questions, nil } // ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档直接导入题库: // 取回 Excel 原件解析建库,文档已在知识库故直接挂接 knowledge_id 不重复上传; // 未指定归属课程时继承同名旧题库的课程关联。 func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, libraryCourseID, updaterID string) (*types.TrainingQuestionBank, error) { if strings.TrimSpace(knowledgeID) == "" { return nil, errors.NewBadRequestError("缺少知识库文档") } rc, fileName, err := s.knowledgeSvc.GetKnowledgeFile(ctx, knowledgeID) if err != nil { return nil, errors.NewBadRequestError("知识库文件读取失败").WithDetails(err.Error()) } defer rc.Close() data, err := io.ReadAll(rc) if err != nil { return nil, errors.NewBadRequestError("知识库文件读取失败").WithDetails(err.Error()) } name = strings.TrimSpace(name) if name == "" { name = strings.TrimSuffix(fileName, "."+path.Ext(fileName)) } questions, err := s.parseQuestionBankExcel(ctx, tenantID, data) if err != nil { return nil, err } oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name) if err != nil { return nil, err } if courseID == "" { courseID = oldCourseID } if libraryCourseID == "" { libraryCourseID = oldLibraryCourseID } bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID} return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID) } // ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。 func (s *trainingService) ListLibraryCourseQuestionBanks(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error) { if libraryCourseID == "" { return nil, errors.NewBadRequestError("缺少课程管理条目") } return s.repo.GetQuestionBankByLibraryCourse(ctx, tenantID, libraryCourseID) } // LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):所选题库整体 // 替换该条目当前挂接的题库,回写课程管理资产(月计划侧更换入口)。 func (s *trainingService) LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error { if libraryCourseID == "" { return errors.NewBadRequestError("缺少课程管理条目") } if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil { return errors.NewNotFoundError("题库不存在") } return s.repo.RelinkQuestionBankToLibraryCourse(ctx, tenantID, libraryCourseID, bankID) } // DeleteQuestionBank 删除题库(连带题目与缓存试卷;试题维护抽屉删除入口,000153)。 func (s *trainingService) DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error { if _, err := s.repo.GetQuestionBank(ctx, tenantID, bankID); err != nil { return errors.NewNotFoundError("题库不存在") } return s.repo.DeleteQuestionBank(ctx, tenantID, bankID) } // SaveQuestion 单题新增/编辑(id 空 = 新增;题库 question_count 同步刷新,000153)。 func (s *trainingService) SaveQuestion(ctx context.Context, tenantID uint64, q *types.TrainingQuestion) (*types.TrainingQuestion, error) { q.Stem = strings.TrimSpace(q.Stem) if q.Stem == "" { return nil, errors.NewBadRequestError("题干不能为空") } if q.Type != types.TrainingQuestionMultiple && q.Type != types.TrainingQuestionJudge { q.Type = types.TrainingQuestionSingle } if q.Difficulty <= 0 { q.Difficulty = 3 } if _, err := s.repo.GetQuestionBank(ctx, tenantID, q.BankID); err != nil { return nil, errors.NewNotFoundError("题库不存在") } if q.ID == "" { // 新增:题序排在库内已有题目之后。 existing, err := s.repo.ListQuestions(ctx, tenantID, q.BankID) if err != nil { return nil, err } q.ID = trainingNewID() q.TenantID = tenantID q.SeqNo = len(existing) + 1 if err := s.repo.CreateQuestion(ctx, q); err != nil { return nil, err } } else { old, err := s.repo.GetQuestion(ctx, tenantID, q.ID) if err != nil { return nil, errors.NewNotFoundError("题目不存在") } q.TenantID = tenantID q.BankID = old.BankID q.SeqNo = old.SeqNo if err := s.repo.UpdateQuestion(ctx, q); err != nil { return nil, err } } s.refreshBankQuestionCount(ctx, tenantID, q.BankID) return q, nil } // DeleteQuestion 删除单题(题库 question_count 同步刷新,000153)。 func (s *trainingService) DeleteQuestion(ctx context.Context, tenantID uint64, questionID string) error { q, err := s.repo.GetQuestion(ctx, tenantID, questionID) if err != nil { return errors.NewNotFoundError("题目不存在") } if err := s.repo.DeleteQuestion(ctx, tenantID, questionID); err != nil { return err } s.refreshBankQuestionCount(ctx, tenantID, q.BankID) return nil } // refreshBankQuestionCount 按现存题目数刷新题库冗余计数(fail-open)。 func (s *trainingService) refreshBankQuestionCount(ctx context.Context, tenantID uint64, bankID string) { count, err := s.repo.CountBankQuestions(ctx, tenantID, bankID) if err != nil { return } _ = s.repo.UpdateQuestionBankCount(ctx, tenantID, bankID, int(count)) } // questionTemplateCol holds resolved column indexes of the 题库导入版 template header. type questionTemplateCol struct { stem int answer int difficulty int knowledge int analysis int score int course int options []questionOptionCol } type questionOptionCol struct { letter byte idx int } // detectTemplateQuestionHeader locates the 题库导入版 template header row within // the first 20 lines: a row carrying stem(题目/题干), answer(正确答案/答案) and // option-letter columns(答案A..答案L). The legacy 简表 header(题型/题干/选项) is // rejected so both layouts stay distinguishable. 20 行:模板表头前有标题与多条 // 填写说明(实测 6+ 行),只扫前几行会把说明行当表头漏检,退化为位置解析导致整列错位。 func detectTemplateQuestionHeader(rows [][]string) (int, *questionTemplateCol, bool) { limit := len(rows) if limit > 20 { limit = 20 } for i := 0; i < limit; i++ { if col, ok := mapTemplateQuestionHeader(rows[i]); ok { return i, col, true } } return 0, nil, false } func mapTemplateQuestionHeader(header []string) (*questionTemplateCol, bool) { col := &questionTemplateCol{stem: -1, answer: -1, difficulty: -1, knowledge: -1, analysis: -1, score: -1, course: -1} hasTypeCol := false hasOptionsCol := false for i, raw := range header { cell := strings.TrimSpace(raw) if cell == "" { continue } switch { case strings.Contains(cell, "题型"): hasTypeCol = true case strings.Contains(cell, "选项"): hasOptionsCol = true case col.stem < 0 && (strings.Contains(cell, "题目") || strings.Contains(cell, "题干")): col.stem = i case strings.HasPrefix(cell, "答案") && isOptionLetterTail(cell): letter := strings.ToUpper(strings.TrimSpace(cell[len("答案"):]))[0] col.options = append(col.options, questionOptionCol{letter: letter, idx: i}) case col.answer < 0 && (strings.Contains(cell, "正确答案") || cell == "答案"): col.answer = i case col.difficulty < 0 && strings.Contains(cell, "难度"): col.difficulty = i case col.course < 0 && strings.Contains(cell, "课程名称"): col.course = i case col.knowledge < 0 && (strings.Contains(cell, "考核点") || strings.Contains(cell, "知识点")): col.knowledge = i case col.analysis < 0 && strings.Contains(cell, "解析"): col.analysis = i case col.score < 0 && strings.Contains(cell, "分值"): col.score = i } } sort.Slice(col.options, func(a, b int) bool { return col.options[a].letter < col.options[b].letter }) // 模板格式 = 题干列 + 答案列且非简表布局(题型+选项同现)。 // 判断题工作表(题目|课程名称|难度|正确答案:)没有选项列,由判断题默认选项(对/错)兜底。 ok := col.stem >= 0 && col.answer >= 0 && !(hasTypeCol && hasOptionsCol) return col, ok } // isOptionLetterTail reports whether the text after a 「答案」 prefix is a single // option letter A-L/a-l (e.g. 答案A, 答案H). func isOptionLetterTail(cell string) bool { tail := strings.ToUpper(strings.TrimSpace(cell[len("答案"):])) return len(tail) == 1 && tail[0] >= 'A' && tail[0] <= 'L' } func questionTypeFromSheetName(name string) string { switch { case strings.Contains(name, "多选"): return types.TrainingQuestionMultiple case strings.Contains(name, "判断"): return types.TrainingQuestionJudge default: return types.TrainingQuestionSingle } } // parseTemplateQuestionSheet walks data rows below the template header. // 兼容两种布局:整表一个题型(按工作表名)与同表分节(「单选题/多选题/判断题」标题行切换)。 func parseTemplateQuestionSheet(rows [][]string, col *questionTemplateCol, qType string) []*types.TrainingQuestion { questions := make([]*types.TrainingQuestion, 0, len(rows)) currentType := qType for _, row := range rows { // 分节标题行(仅一个短单元格,如「多选题」)切换后续题型。 if t := questionSectionType(row); t != "" { currentType = t continue } get := func(idx int) string { if idx >= 0 && idx < len(row) { return strings.TrimSpace(row[idx]) } return "" } stem := get(col.stem) if stem == "" { continue } answer := strings.ToUpper(get(col.answer)) // 重复表头行(同表多节)跳过:题干列是「题目」且答案列是「正确答案」等表头字样。 if strings.Contains(stem, "题目") && strings.Contains(answer, "答案") { continue } if answer == "" { continue // 缺答案的题目跳过,保证可判分 } options := make([]string, 0, len(col.options)) for _, opt := range col.options { if v := get(opt.idx); v != "" { options = append(options, v) } } // 模板选项列是纯文本,补字母前缀使线上答题/判分与简表版同口径(A. xx)。 options = ensureOptionLetterPrefixes(options) if qType == types.TrainingQuestionJudge && len(options) == 0 { options = []string{"A. 对", "B. 错"} } q := &types.TrainingQuestion{ Type: currentType, Stem: stem, Options: trainingJSONFromSlice(options), Answer: normalizeTemplateAnswer(answer, options), Difficulty: normalizeTemplateDifficulty(get(col.difficulty)), KnowledgePoint: get(col.knowledge), Analysis: get(col.analysis), } // 模板无「课程名称→知识点」独立列时,用课程名称列充填知识点(薄弱点分析按此聚合)。 if q.KnowledgePoint == "" && col.course >= 0 { q.KnowledgePoint = get(col.course) } if v := parseFirstFloat(get(col.score)); v > 0 { q.Score = v } else { q.Score = 5 } questions = append(questions, q) } return questions } // questionSectionType 同表分节布局的题型标题行识别: // 仅一个非空单元格且为「单选/多选/判断」类短标题时返回对应题型,否则空串。 func questionSectionType(row []string) string { nonEmpty := make([]string, 0, len(row)) for _, cell := range row { if v := strings.TrimSpace(cell); v != "" { nonEmpty = append(nonEmpty, v) } } if len(nonEmpty) != 1 || len([]rune(nonEmpty[0])) > 6 { return "" } return questionTypeFromSheetName(nonEmpty[0]) } var questionOptionLetterPrefixRe = regexp.MustCompile(`^([A-Za-z])[..、::]`) // ensureOptionLetterPrefixes prefixes bare-text options with letters in order; // leaves the list untouched when any option already carries a letter prefix. func ensureOptionLetterPrefixes(options []string) []string { for _, opt := range options { if questionOptionLetterPrefixRe.MatchString(opt) { return options } } prefixed := make([]string, len(options)) for i, opt := range options { prefixed[i] = fmt.Sprintf("%c. %s", 'A'+i, opt) } return prefixed } // normalizeTemplateAnswer normalizes the 「正确答案」 cell to the scoring key: // letter answers(A / ABCD) pass through; text answers (judge-style 对/错/正确/ // 错误/√/×) map to the matching option's submission key ("A. 对" → "A"). func normalizeTemplateAnswer(raw string, options []string) string { raw = strings.ToUpper(strings.TrimSpace(raw)) if raw == "" || isAnswerLetters(raw) { return raw } canonical := canonicalJudgeAnswer(raw) for _, opt := range options { trimmed := strings.TrimSpace(opt) m := questionOptionLetterPrefixRe.FindStringSubmatch(trimmed) if m == nil { continue } text := strings.TrimSpace(trimmed[len(m[0]):]) if text != "" && strings.EqualFold(text, canonical) { return strings.ToUpper(m[1]) } } return raw } // isAnswerLetters reports whether raw is 1-12 option letters A-L (e.g. A, ABCD). func isAnswerLetters(raw string) bool { if len(raw) == 0 || len(raw) > 12 { return false } for _, r := range raw { if r < 'A' || r > 'L' { return false } } return true } // canonicalJudgeAnswer folds common judge answer spellings into 对/错. func canonicalJudgeAnswer(raw string) string { switch raw { case "对", "正确", "是", "√", "T", "TRUE", "Y", "YES": return "对" case "错", "错误", "否", "×", "X", "F", "FALSE", "N", "NO": return "错" } return raw } // normalizeTemplateDifficulty accepts 1-5 numbers or 高/中/低 text; fallback 3. func normalizeTemplateDifficulty(raw string) int { switch strings.ToUpper(strings.TrimSpace(raw)) { case "高", "难", "H", "HARD": return 4 case "中", "中等", "M", "MEDIUM": return 3 case "低", "易", "简单", "L", "EASY": return 2 } if v := int(parseFirstFloat(raw)); v >= 1 && v <= 5 { return v } return 3 } // parseLegacyQuestionSheet parses the positional 简表 layout: // 题型 | 题干 | 选项(JSON数组或A|B|C分隔) | 答案 | 分值 | 难度 | 知识点 | 解析。 func parseLegacyQuestionSheet(rows [][]string) []*types.TrainingQuestion { questions := make([]*types.TrainingQuestion, 0, len(rows)) for i, row := range rows { if i == 0 { continue // 表头 } get := func(idx int) string { if idx < len(row) { return strings.TrimSpace(row[idx]) } return "" } qType := normalizeQuestionType(get(0)) stem := get(1) if stem == "" { continue } options := parseQuestionOptions(get(2)) answer := strings.ToUpper(get(3)) if answer == "" { continue // 缺答案的题目跳过,保证可判分 } q := &types.TrainingQuestion{ Type: qType, Stem: stem, Options: trainingJSONFromSlice(options), Answer: answer, Difficulty: 3, KnowledgePoint: get(6), Analysis: get(7), } if v := parseFirstFloat(get(4)); v > 0 { q.Score = v } else { q.Score = 5 } if v := int(parseFirstFloat(get(5))); v >= 1 && v <= 5 { q.Difficulty = v } questions = append(questions, q) } return questions } // normalizeQuestionType maps Chinese/alias type names to enum values. func normalizeQuestionType(raw string) string { switch strings.TrimSpace(raw) { case "多选", "多选题", "multiple", "multi": return types.TrainingQuestionMultiple case "判断", "判断题", "judge", "bool": return types.TrainingQuestionJudge default: return types.TrainingQuestionSingle } } // parseQuestionOptions accepts either a JSON array or "A.选项|B.选项" style. func parseQuestionOptions(raw string) []string { raw = strings.TrimSpace(raw) if raw == "" { return []string{} } if strings.HasPrefix(raw, "[") { return trainingJSONStrings(raw) } parts := strings.Split(raw, "|") out := make([]string, 0, len(parts)) for _, p := range parts { if t := strings.TrimSpace(p); t != "" { out = append(out, t) } } return out } // trainingJSONStrings decodes a json array of strings with a safe fallback. func trainingJSONStrings(raw string) []string { out := []string{} if len(raw) == 0 { return out } _ = json.Unmarshal([]byte(raw), &out) return out } // parseFirstFloat extracts the first numeric value from a cell. func parseFirstFloat(raw string) float64 { var v float64 started := false for _, r := range raw { if r >= '0' && r <= '9' { v = v*10 + float64(r-'0') started = true } else if r == '.' && started { // 简化:小数部分按一位精度处理不到的情况可接受(分值/难度均为整数场景) break } else if started { break } } return v } // GeneratePaper draws questions deterministically by knowledge-point/ // difficulty weights (规则引擎组卷,一键 A/B 卷)。 func (s *trainingService) GeneratePaper(ctx context.Context, tenantID uint64, bankID, sessionID string, count int, version, operatorID string) (*types.TrainingPaper, error) { bank, err := s.repo.GetQuestionBank(ctx, tenantID, bankID) if err != nil { return nil, errors.NewNotFoundError("题库不存在") } if count <= 0 { count = 20 } questions, err := s.repo.ListQuestions(ctx, tenantID, bankID) if err != nil { return nil, err } if len(questions) == 0 { return nil, errors.NewBadRequestError("题库为空,请先导入题目") } if count > len(questions) { count = len(questions) } // 按难度分层抽样:简单/中等/困难 = 3:5:2(可按配置扩展)。 byDifficulty := map[int][]*types.TrainingQuestion{} for _, q := range questions { byDifficulty[q.Difficulty] = append(byDifficulty[q.Difficulty], q) } pick := make([]*types.TrainingQuestion, 0, count) rng := rand.New(rand.NewSource(time.Now().UnixNano() + int64(len(version)))) appendPick := func(list []*types.TrainingQuestion, n int) { if len(list) == 0 || n <= 0 { return } idx := rng.Perm(len(list)) for i := 0; i < n && i < len(idx); i++ { pick = append(pick, list[idx[i]]) } } easy := byDifficulty[1] easy = append(easy, byDifficulty[2]...) medium := byDifficulty[3] hard := byDifficulty[4] hard = append(hard, byDifficulty[5]...) appendPick(hard, count*2/10) appendPick(easy, count*3/10) appendPick(medium, count-len(pick)) if len(pick) < count { // 兜底:不足时从剩余题目补齐 chosen := map[string]struct{}{} for _, q := range pick { chosen[q.ID] = struct{}{} } idx := rng.Perm(len(questions)) for _, i := range idx { if len(pick) >= count { break } if _, ok := chosen[questions[i].ID]; !ok { pick = append(pick, questions[i]) } } } // 固定题序(题干原样)。 sort.SliceStable(pick, func(i, j int) bool { return pick[i].SeqNo < pick[j].SeqNo }) // 考试满分固定 100:按题目数自动划分各题分值(精确分摊,合计恰为 100), // 及格线取配置中心 pass_line.default(未配置回退 60)。 const paperTotal = 100.0 scores := dividePaperScores(len(pick), paperTotal) questionScores := make(map[string]float64, len(pick)) ids := make([]string, 0, len(pick)) for i, q := range pick { questionScores[q.ID] = scores[i] ids = append(ids, q.ID) } if version == "" { version = "A" } passScore := s.ruleFloat(ctx, tenantID, types.RuleKeyPassLine, "default", 60) if passScore <= 0 || passScore >= paperTotal { passScore = 60 } genRuleJSON, err := json.Marshal(map[string]any{ "count": count, "strategy": "difficulty_mix", "total_score": paperTotal, "question_scores": questionScores, }) if err != nil { genRuleJSON = types.JSON("{}") } paper := &types.TrainingPaper{ ID: trainingNewID(), TenantID: tenantID, SessionID: sessionID, BankID: bankID, Name: fmt.Sprintf("%s(%s卷)", bank.Name, version), TotalScore: paperTotal, PassScore: mathRound1(passScore), Version: version, GenRule: types.JSON(genRuleJSON), QuestionIDs: trainingJSONFromSlice(ids), CreatorID: operatorID, } if err := s.repo.CreatePaper(ctx, paper); err != nil { return nil, err } return paper, nil } // dividePaperScores 将满分 total 按题数自动划分:以 0.01 分为最小单位均摊, // 余数分摊到前几题,保证合计恰好等于 total。 func dividePaperScores(n int, total float64) []float64 { if n <= 0 { return nil } totalCents := int(math.Round(total * 100)) base := totalCents / n remainder := totalCents - base*n out := make([]float64, n) for i := 0; i < n; i++ { cents := base if i < remainder { cents++ } out[i] = float64(cents) / 100 } return out } // paperQuestionScores 试卷级题目分值(组卷时按满分 100 自动划分,存于 gen_rule); // 旧试卷无该配置时返回 nil,判分/展示回退题目自身分值。 func paperQuestionScores(paper *types.TrainingPaper) map[string]float64 { raw := strings.TrimSpace(string(paper.GenRule)) if raw == "" || raw == "{}" { return nil } var genRule struct { QuestionScores map[string]float64 `json:"question_scores"` } if err := json.Unmarshal([]byte(raw), &genRule); err != nil { return nil } return genRule.QuestionScores } // SubmitExam grades the objective answers instantly (本人交卷入口)。 func (s *trainingService) SubmitExam(ctx context.Context, tenantID uint64, userID, paperID string, answers map[string]string) (*types.TrainingExamRecord, error) { paper, err := s.repo.GetPaper(ctx, tenantID, paperID) if err != nil { return nil, errors.NewNotFoundError("试卷不存在") } member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return nil, errors.NewForbiddenError("未建立培训档案,无法交卷") } return s.submitExamAs(ctx, tenantID, member, paper, answers) } // AnswerQuestion 单题即时判分(答题页实时反馈):返回对错/得分/正确答案与解析。 // 不落答卷、不计错题本——整卷交卷时仍走 SubmitExam 统一判分与记录; // 逐题揭示答案的同时保证答案不提前下发(未作答的题拿不到正确答案)。 func (s *trainingService) AnswerQuestion(ctx context.Context, tenantID uint64, paperID, questionID, answer string) (*types.TrainingQuestionFeedback, error) { paper, err := s.repo.GetPaper(ctx, tenantID, paperID) if err != nil { return nil, errors.NewNotFoundError("试卷不存在") } belongs := false for _, id := range trainingJSONStrings(string(paper.QuestionIDs)) { if id == questionID { belongs = true break } } if !belongs { return nil, errors.NewBadRequestError("该题目不属于当前试卷") } questions, err := s.repo.ListQuestionsByIDs(ctx, tenantID, []string{questionID}) if err != nil || len(questions) == 0 || questions[0] == nil { return nil, errors.NewNotFoundError("题目不存在") } q := questions[0] // 判分用组卷时划分的试卷级分值(旧试卷回退题目自身分值)。 score := q.Score if paperScores := paperQuestionScores(paper); paperScores != nil { if v, ok := paperScores[q.ID]; ok { score = v } } given := strings.ToUpper(strings.TrimSpace(answer)) want := strings.ToUpper(strings.TrimSpace(q.Answer)) correct := given != "" && normalizeAnswerSet(given) == normalizeAnswerSet(want) if !correct { score = 0 } return &types.TrainingQuestionFeedback{ QuestionID: q.ID, Correct: correct, Score: score, CorrectAnswer: q.Answer, Analysis: q.Analysis, }, nil } // submitExamAs 以指定成员身份判分落卷(本人/代交卷共用)。 // 重考策略:未通过的答卷允许覆盖重考(取最新成绩),已通过则锁定。 func (s *trainingService) submitExamAs(ctx context.Context, tenantID uint64, member *types.TrainingMember, paper *types.TrainingPaper, answers map[string]string) (*types.TrainingExamRecord, error) { if existing, err := s.repo.GetExamRecord(ctx, tenantID, paper.ID, member.ID); err == nil && existing != nil { if existing.Score != nil && paper.PassScore > 0 && *existing.Score >= paper.PassScore { return nil, errors.NewBadRequestError("考试已通过,无需重考") } } ids := trainingJSONStrings(string(paper.QuestionIDs)) questions, err := s.repo.ListQuestionsByIDs(ctx, tenantID, ids) if err != nil { return nil, err } // 判分按组卷时划分的试卷级分值(旧试卷回退题目自身分值)。 paperScores := paperQuestionScores(paper) scoreFor := func(q *types.TrainingQuestion) float64 { if paperScores != nil { if v, ok := paperScores[q.ID]; ok { return v } } return q.Score } score := 0.0 now := time.Now() wrongIDs := []string{} for _, q := range questions { given := strings.ToUpper(strings.TrimSpace(answers[q.ID])) want := strings.ToUpper(strings.TrimSpace(q.Answer)) if given == "" || normalizeAnswerSet(given) != normalizeAnswerSet(want) { wrongIDs = append(wrongIDs, q.ID) s.mergeWrongBook(ctx, tenantID, member, q, paper.SessionID) } else { score += scoreFor(q) } } record := &types.TrainingExamRecord{ ID: trainingNewID(), TenantID: tenantID, PaperID: paper.ID, SessionID: paper.SessionID, MemberID: member.ID, StartedAt: &now, SubmittedAt: &now, Score: &score, DurationSec: 0, } if err := s.repo.UpsertExamRecord(ctx, record); err != nil { return nil, err } // 交卷响应回显对错(瞬态字段,不落库)。 record.WrongQuestionIDs = wrongIDs // 成绩达标即视为该场次课程完成。 if score >= paper.PassScore && paper.SessionID != "" { _ = s.markSessionCompleted(ctx, tenantID, paper.SessionID, member.ID) } // 积分规则:100分+20 / 90分+10(规则可配)。 pointRules := trainingJSONMap(s.ruleBytes(ctx, tenantID, types.RuleKeyPointRules)) pointVal := 0 ruleKey := "" if score >= 100 || (paper.TotalScore > 0 && score >= paper.TotalScore) { pointVal = int(trainingJSONFloat(pointRules, "score_100", 20)) ruleKey = "score_100" } else if paper.TotalScore > 0 && score/paper.TotalScore >= 0.9 { pointVal = int(trainingJSONFloat(pointRules, "score_90", 10)) ruleKey = "score_90" } if pointVal > 0 { _ = s.repo.AddPointRecord(ctx, &types.TrainingPointRecord{ ID: trainingNewID(), TenantID: tenantID, MemberID: member.ID, RuleKey: ruleKey, Points: pointVal, SourceType: "exam", SourceID: paper.ID, }) } return record, nil } // mergeWrongBook upserts personal & department wrong-question entries. func (s *trainingService) mergeWrongBook(ctx context.Context, tenantID uint64, member *types.TrainingMember, q *types.TrainingQuestion, sessionID string) { if q == nil { return } _ = s.repo.UpsertWrongBook(ctx, &types.TrainingWrongBook{ ID: trainingNewID(), TenantID: tenantID, MemberID: member.ID, DeptID: member.DeptID, QuestionID: q.ID, KnowledgePoint: q.KnowledgePoint, LastSessionID: sessionID, }) _ = s.repo.UpsertWrongBook(ctx, &types.TrainingWrongBook{ ID: trainingNewID(), TenantID: tenantID, MemberID: "", DeptID: member.DeptID, QuestionID: q.ID, KnowledgePoint: q.KnowledgePoint, LastSessionID: sessionID, }) } // markSessionCompleted marks the member's enrollment completed after a // passing exam (考试达标 → 课程完成)。 func (s *trainingService) markSessionCompleted(ctx context.Context, tenantID uint64, sessionID, memberID string) error { roster, err := s.repo.ListEnrollments(ctx, tenantID, sessionID) if err != nil { return err } for _, e := range roster { if e.MemberID != memberID { continue } if e.Status == types.TrainingEnrollCompleted { return nil } e.Status = types.TrainingEnrollCompleted now := time.Now() e.CompletedAt = &now return s.repo.UpdateEnrollment(ctx, e) } return nil } // ListPapersForSession exposes the paper list of a session. func (s *trainingService) ListPapersForSession(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingPaper, error) { return s.repo.ListPapers(ctx, tenantID, sessionID) } // courseSelfStudyPaperVersion 线上自学卷的版本标识(与线下 A/B 卷区分, // 也是 GetSelfStudyPaperByBank 的检索键)。 const courseSelfStudyPaperVersion = "ONLINE" // GetCourseExamPaper 线上自学考试入口:确保课程线上卷存在并返回学员视角 // 题目(卷不存在时按题库全量题数现场组卷,幂等)。 func (s *trainingService) GetCourseExamPaper(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingPaper, []*types.TrainingQuestion, error) { // 绑定题库即默认可答题:只要课程(或其课程管理条目,000153)关联了题库就允许 // 取卷答题,exam_enabled 仅决定详情页是否主动展示考试入口。 course, cErr := s.repo.GetCourse(ctx, tenantID, courseID) if cErr != nil || course == nil { return nil, nil, errors.NewNotFoundError("课程不存在") } bank, err := s.courseExamBank(ctx, tenantID, course) if err != nil || bank == nil { return nil, nil, errors.NewNotFoundError("该课程未绑定题库,请联系培训管理员在课程管理中关联题库") } paper, err := s.repo.GetSelfStudyPaperByBank(ctx, tenantID, bank.ID) if err != nil || paper == nil { count := bank.QuestionCount if count <= 0 { return nil, nil, errors.NewBadRequestError("题库暂无试题,请联系培训管理员导入") } if paper, err = s.GeneratePaper(ctx, tenantID, bank.ID, "", count, courseSelfStudyPaperVersion, userID); err != nil { return nil, nil, err } } // 复用学员答题视图:非管理角色剥离答案与解析。 return s.GetPaperForExam(ctx, tenantID, userID, paper.ID) } // GetMyCourseExamRecord returns the caller's latest record on the course // self-study paper (nil, false) when未考/未绑题库。 func (s *trainingService) GetMyCourseExamRecord(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingExamRecord, bool, error) { course, cErr := s.repo.GetCourse(ctx, tenantID, courseID) if cErr != nil || course == nil { return nil, false, nil } bank, err := s.courseExamBank(ctx, tenantID, course) if err != nil || bank == nil { return nil, false, nil } paper, err := s.repo.GetSelfStudyPaperByBank(ctx, tenantID, bank.ID) if err != nil || paper == nil { return nil, false, nil } member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return nil, false, nil } record, err := s.repo.GetExamRecord(ctx, tenantID, paper.ID, member.ID) if err != nil || record == nil { return nil, false, nil } passed := record.Score != nil && paper.PassScore > 0 && *record.Score >= paper.PassScore return record, passed, nil } // ListExamRecords returns the session's records. func (s *trainingService) ListExamRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingExamRecord, error) { return s.repo.ListExamRecords(ctx, tenantID, sessionID) } // ListPapersForCourse 课程维度试卷列表:场次卷 + 线上自学卷归并(课程考试情况查询)。 func (s *trainingService) ListPapersForCourse(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingPaper, error) { return s.repo.ListPapersByCourse(ctx, tenantID, courseID) } // ListPaperRecords 单张试卷的答题记录(按试卷查询,覆盖 session 为空的线上自学卷)。 func (s *trainingService) ListPaperRecords(ctx context.Context, tenantID uint64, paperID string) ([]*types.TrainingExamRecord, error) { return s.repo.ListExamRecordsByPaper(ctx, tenantID, paperID) } // ListMyExamRecords returns the caller's all exam records (未建培训档案返回空)。 func (s *trainingService) ListMyExamRecords(ctx context.Context, tenantID uint64, userID string) ([]*types.TrainingExamRecord, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return []*types.TrainingExamRecord{}, nil } return s.repo.ListMyExamRecords(ctx, tenantID, member.ID) } // ListQuestions returns one bank's questions. func (s *trainingService) ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error) { return s.repo.ListQuestions(ctx, tenantID, bankID) } // ExamAnalysis computes the class weak-point view (薄弱知识点错误率)。 func (s *trainingService) ExamAnalysis(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingExamAnalysis, error) { weak, err := s.repo.DeptWeakPoints(ctx, tenantID, sessionID) if err != nil { return nil, err } records, _ := s.repo.ListExamRecords(ctx, tenantID, sessionID) participants := float64(len(records)) if participants == 0 { participants = 1 } for _, w := range weak { if w.WrongCount > int64(participants) { w.ErrorRate = 1 } else { w.ErrorRate = float64(w.WrongCount) / participants } } return weak, nil } // ListWrongBook returns the member's wrong-question book (带题干展示)。 func (s *trainingService) ListWrongBook(ctx context.Context, tenantID uint64, memberID string) ([]*types.TrainingWrongBook, error) { member, err := s.resolveMember(ctx, tenantID, memberID) if err != nil { return nil, err } return s.repo.ListWrongBookWithQuestions(ctx, tenantID, member.ID) } // resolveMember maps a user-id-or-member-id into a member profile. func (s *trainingService) resolveMember(ctx context.Context, tenantID uint64, memberOrUserID string) (*types.TrainingMember, error) { if m, err := s.repo.GetMember(ctx, tenantID, memberOrUserID); err == nil { return m, nil } return s.repo.GetMemberByUserID(ctx, tenantID, memberOrUserID) } // --------------------------------------------------------------------------- // 学习/评分 // --------------------------------------------------------------------------- // SaveLearningProgress stores the playback position; ≥95% completes the task // and awards the course points once (unique rule key dedups)。 func (s *trainingService) SaveLearningProgress(ctx context.Context, tenantID uint64, userID, taskID, materialID string, positionSec, percent int) error { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return errors.NewForbiddenError("未建立培训档案") } if percent < 0 { percent = 0 } if percent > 100 { percent = 100 } if err := s.repo.UpsertLearningProgress(ctx, &types.TrainingLearningProgress{ ID: trainingNewID(), TenantID: tenantID, TaskID: taskID, MaterialID: materialID, PositionSec: positionSec, Percent: percent, }); err != nil { return err } if percent >= 95 { tasks, err := s.repo.ListLearningTasks(ctx, tenantID, member.ID) if err != nil { return err } for _, t := range tasks { if t.ID != taskID || t.Status == types.TrainingLearningDone { continue } now := time.Now() t.Status = types.TrainingLearningDone t.CompletedAt = &now if err := s.repo.UpsertLearningTask(ctx, t); err != nil { return err } // 自学/选修积分(规则可配)。 _ = s.repo.AddPointRecord(ctx, &types.TrainingPointRecord{ ID: trainingNewID(), TenantID: tenantID, MemberID: member.ID, RuleKey: "self_study", Points: 3, SourceType: "learning", SourceID: taskID, }) } } return nil } // ListMyLearningTasks returns the caller's learning tasks. func (s *trainingService) ListMyLearningTasks(ctx context.Context, tenantID uint64, userID string) ([]*types.TrainingLearningTask, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return []*types.TrainingLearningTask{}, nil } return s.repo.ListLearningTasks(ctx, tenantID, member.ID) } // ListCourseLearningTasks returns all members' learning tasks of one course // (管理端「学习考试」课程学习情况;任务不存在但已发布课程的名单成员由前端按待学习渲染口径,此处按实际任务行返回)。 func (s *trainingService) ListCourseLearningTasks(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingLearningTask, error) { if courseID == "" { return []*types.TrainingLearningTask{}, nil } return s.repo.ListCourseLearningTasks(ctx, tenantID, courseID) } // ListMyCourseProgress returns the caller's per-material progress in one // course. 未建培训档案时返回空列表(前端按无进度渲染,不阻断预览)。 func (s *trainingService) ListMyCourseProgress(ctx context.Context, tenantID uint64, userID, courseID string) ([]*types.TrainingLearningProgress, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return []*types.TrainingLearningProgress{}, nil } return s.repo.ListProgressByCourse(ctx, tenantID, member.ID, courseID) } // SaveFeedback stores the member's course rating & question. func (s *trainingService) SaveFeedback(ctx context.Context, tenantID uint64, userID, sessionID string, rating int, comment string) (*types.TrainingCourseFeedback, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return nil, errors.NewForbiddenError("未建立培训档案") } if rating < 1 || rating > 5 { return nil, errors.NewBadRequestError("评分需在 1-5 之间") } fb := &types.TrainingCourseFeedback{ ID: trainingNewID(), TenantID: tenantID, SessionID: sessionID, MemberID: member.ID, Rating: rating, Comment: comment, } if err := s.repo.UpsertFeedback(ctx, fb); err != nil { return nil, err } return fb, nil } // ReplyFeedback answers one feedback row (课程留言答疑)。 func (s *trainingService) ReplyFeedback(ctx context.Context, tenantID uint64, feedbackID, reply, operatorID string) (*types.TrainingCourseFeedback, error) { if reply == "" { return nil, errors.NewBadRequestError("回复内容不能为空") } now := time.Now() fb := &types.TrainingCourseFeedback{ID: feedbackID, TenantID: tenantID, Reply: reply, RepliedAt: &now, RepliedBy: operatorID} if err := s.repo.ReplyFeedback(ctx, fb); err != nil { return nil, err } return fb, nil } // ListPendingFeedbacks returns the caller's unanswered questions. func (s *trainingService) ListPendingFeedbacks(ctx context.Context, tenantID uint64, userID string) ([]*types.TrainingCourseFeedback, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return []*types.TrainingCourseFeedback{}, nil } // 角色按字典权限分配展开后判定(自定义角色继承讲师权限组即视为讲师)。 if !types.HasTrainingRole(s.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList()), types.TrainingRoleLecturer) { return []*types.TrainingCourseFeedback{}, nil } return s.repo.PendingFeedbacks(ctx, tenantID, member.ID) } // --------------------------------------------------------------------------- // 看板 // --------------------------------------------------------------------------- // HRDashboard assembles the 人事工作台 aggregates. func (s *trainingService) HRDashboard(ctx context.Context, tenantID uint64, year, month int) (map[string]interface{}, error) { now := time.Now() if year <= 0 { year = now.Year() } if month <= 0 { month = int(now.Month()) } out := map[string]interface{}{} progress, err := s.DeptDemandProgress(ctx, tenantID, year) if err != nil { return nil, err } out["demand_progress"] = progress completion, err := s.repo.MonthCompletion(ctx, tenantID, year, month) if err != nil { return nil, err } out["month_completion"] = completion courses, total, err := s.repo.ListCourses(ctx, tenantID, &interfaces.TrainingListQuery{Status: types.TrainingCoursePublished, PageSize: 1000}) if err != nil { return nil, err } online, offline := 0, 0 for _, c := range courses { if c.Mode == types.TrainingCourseModeOnline { online++ } else { offline++ } } out["course_total"] = total out["course_online"] = online out["course_offline"] = offline sessions, _ := s.repo.ListSessions(ctx, tenantID, &interfaces.TrainingListQuery{Year: year, Month: month}) out["month_sessions"] = sessions demands, demandTotal, _ := s.repo.ListDemands(ctx, tenantID, &interfaces.TrainingListQuery{Year: year, Status: types.TrainingDemandSubmitted, PageSize: 10}) out["pending_demands"] = demands out["pending_demands_total"] = demandTotal return out, nil } // DeptDashboard assembles the 部门主管工作台 aggregates. func (s *trainingService) DeptDashboard(ctx context.Context, tenantID uint64, userID string, year, month int) (map[string]interface{}, error) { now := time.Now() if year <= 0 { year = now.Year() } if month <= 0 { month = int(now.Month()) } member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil { return nil, errors.NewForbiddenError("未建立培训档案") } out := map[string]interface{}{} monthPlans, _ := s.repo.ListMonthPlans(ctx, tenantID, &interfaces.TrainingListQuery{Year: year, Month: month, DeptID: member.DeptID}) out["month_plans"] = monthPlans pending := 0 for _, p := range monthPlans { if p.Status == types.TrainingMonthPlanSubmitted { pending++ } } out["pending_approvals"] = pending sessions, _ := s.repo.ListSessions(ctx, tenantID, &interfaces.TrainingListQuery{Year: year, Month: month}) out["month_sessions"] = sessions completion, _ := s.repo.MonthCompletion(ctx, tenantID, year, month) out["month_completion"] = completion unfinished, _ := s.repo.UnfinishedEnrollments(ctx, tenantID, year, month) out["unfinished_count"] = len(unfinished) return out, nil } // ExecDashboard assembles the 管理驾驶舱 aggregates. func (s *trainingService) ExecDashboard(ctx context.Context, tenantID uint64, year int) (map[string]interface{}, error) { now := time.Now() if year <= 0 { year = now.Year() } out := map[string]interface{}{} monthCompletion, _ := s.repo.MonthCompletion(ctx, tenantID, year, int(now.Month())) out["month_completion"] = monthCompletion deptRanking, err := s.repo.DeptCompletionRanking(ctx, tenantID, year) if err != nil { return nil, err } out["dept_ranking"] = deptRanking lecturers, err := s.repo.LecturerRanking(ctx, tenantID, year, 5) if err != nil { return nil, err } out["lecturer_ranking"] = lecturers points, err := s.repo.SumPoints(ctx, tenantID) if err != nil { return nil, err } out["points_total"] = points // 月度盘点摘要(规则引擎版;LLM 初稿由三期调度器接通)。 summary := "本月盘点:请查看部门达成率排名与讲师积分榜。" if monthCompletion != nil && monthCompletion.Total > 0 { summary = fmt.Sprintf("本月完成率 %d%%(已完成 %d/%d);未完成课程已自动滚入下月并置顶提醒。", monthCompletion.Percent, monthCompletion.Completed, monthCompletion.Total) } out["ai_summary"] = summary return out, nil } // MyProfile builds the caller's ability profile (能力画像)。 func (s *trainingService) MyProfile(ctx context.Context, tenantID uint64, userID string) (*types.TrainingProfile, error) { member, err := s.resolveMember(ctx, tenantID, userID) if err != nil { return nil, errors.NewForbiddenError("未建立培训档案") } profile, err := s.repo.MemberAggregates(ctx, tenantID, member.ID) if err != nil { return nil, err } profile.Points, _ = s.repo.SumPointsByMember(ctx, tenantID, member.ID) if dept, err := s.org.ListDepts(ctx, tenantID); err == nil { for _, d := range dept { if d.ID == member.DeptID { profile.DeptName = d.Name break } } } return profile, nil } // --------------------------------------------------------------------------- // 规则配置 / 通知 // --------------------------------------------------------------------------- // ListRuleConfigs returns all rule configs. func (s *trainingService) ListRuleConfigs(ctx context.Context, tenantID uint64) ([]*types.TrainingRuleConfig, error) { return s.repo.ListRuleConfigs(ctx, tenantID) } // SaveRuleConfig upserts one rule config (业务规则改配置不改代码)。 // 职称角色字典(role_dict)在保存前做结构校验(系统角色不可删/权限分配合法)。 func (s *trainingService) SaveRuleConfig(ctx context.Context, tenantID uint64, key string, value []byte, updaterID string) (*types.TrainingRuleConfig, error) { if key == types.RuleKeyRoleDict { if _, err := types.ParseRoleDict(value); err != nil { return nil, errors.NewBadRequestError(err.Error()) } } cfg := &types.TrainingRuleConfig{ ID: trainingNewID(), TenantID: tenantID, RuleKey: key, RuleValue: types.JSON(value), UpdatedBy: updaterID, } if err := s.repo.UpsertRuleConfig(ctx, cfg); err != nil { return nil, err } return cfg, nil } // ruleBytes returns the raw rule JSON for map decoding. func (s *trainingService) ruleBytes(ctx context.Context, tenantID uint64, key string) []byte { cfg, err := s.repo.GetRuleConfig(ctx, tenantID, key) if err != nil || cfg == nil { return nil } return cfg.RuleValue } // RoleDict 读取职称角色字典(配置中心 role_dict);缺失/损坏时回退系统默认 // 角色,保证鉴权链路在任何配置状态下都可用。存量 v1 字典(主管/文员/高管口径) // 读取时升级为 v2(课长/经理/人事/讲师)视图,人事在配置中心保存后自然固化。 func (s *trainingService) RoleDict(ctx context.Context, tenantID uint64) []types.TrainingRoleDef { raw := s.ruleBytes(ctx, tenantID, types.RuleKeyRoleDict) if len(raw) > 0 { if dict, err := types.ParseRoleDict(raw); err == nil { if types.NeedsRoleDictUpgrade(dict) { return types.UpgradeRoleDictV2(dict) } return dict } } return types.DefaultRoleDict() } // ExpandTrainingRoles 把成员角色按字典的权限分配(Inherits)传递展开成 // 权限并集,供 requireRoles 等鉴权点比对(自定义角色由此获得真实权限)。 // 存量成员携带的 clerk(部门文员,已移除)按别名映射为课长,平滑过渡。 func (s *trainingService) ExpandTrainingRoles(ctx context.Context, tenantID uint64, roles []string) []string { if len(roles) == 0 { return roles } aliased := make([]string, 0, len(roles)) for _, r := range roles { if mapped, ok := types.LegacyRoleAlias(r); ok && !types.HasTrainingRole(roles, mapped) { aliased = append(aliased, mapped) continue } aliased = append(aliased, r) } return types.ExpandRoles(s.RoleDict(ctx, tenantID), aliased) } // ListNotifications returns the caller's notifications. func (s *trainingService) ListNotifications(ctx context.Context, tenantID uint64, userID string, unreadOnly bool, limit int) ([]*types.TrainingNotification, error) { return s.repo.ListNotifications(ctx, tenantID, userID, unreadOnly, limit) } // MarkNotificationsRead marks all the caller's notifications read. func (s *trainingService) MarkNotificationsRead(ctx context.Context, tenantID uint64, userID string) error { return s.repo.MarkNotificationsRead(ctx, tenantID, userID) } // Notify appends one notification row; the wecom push consumer picks it up. func (s *trainingService) Notify(ctx context.Context, tenantID uint64, targetUserID, scene, title, content, refType, refID string) error { return s.repo.CreateNotification(ctx, &types.TrainingNotification{ ID: trainingNewID(), TenantID: tenantID, TargetUserID: targetUserID, Channel: "inapp", Scene: scene, Title: title, Content: content, RefType: refType, RefID: refID, SentAt: time.Now(), }) } // BroadcastNotification 向指定平台用户批量推送同一条通知(收集下年度计划等 // 运营场景),站内 + 企微外箱(调度器 dispatchPending 消费)。手动广播是离散 // 的发送动作:ref_id 追加发送时间戳,避免与唯一索引 (tenant,target,scene,ref) // 冲突把已收过通知的人静默去重;返回成功入箱条数。 func (s *trainingService) BroadcastNotification(ctx context.Context, tenantID uint64, userIDs []string, scene, title, content, refType, refID string) (int, error) { if len(userIDs) == 0 { return 0, errors.NewBadRequestError("请选择推送人员") } if scene == "" { scene = "demand_collect" } if refID != "" { refID = fmt.Sprintf("%s-%d", refID, time.Now().UnixNano()) } push := s.loadPushEnabled(ctx, tenantID) now := time.Now() status := "" if push { status = pushStatusPending } rows := make([]*types.TrainingNotification, 0, len(userIDs)) for _, uid := range userIDs { if uid == "" { continue } rows = append(rows, &types.TrainingNotification{ ID: trainingNewID(), TenantID: tenantID, TargetUserID: uid, Channel: "inapp", Scene: scene, Title: title, Content: content, RefType: refType, RefID: refID, SentAt: now, PushStatus: status, }) } if len(rows) == 0 { return 0, errors.NewBadRequestError("请选择推送人员") } if err := s.repo.CreateNotifications(ctx, rows); err != nil { return 0, err } return len(rows), nil } // --------------------------------------------------------------------------- // 小工具 // --------------------------------------------------------------------------- func mathRound1(v float64) float64 { return float64(int(v*10+0.5)) / 10 } // normalizeAnswerSet compares answers order-insensitively for multi-choice. func normalizeAnswerSet(a string) string { chars := strings.Split(a, "") sort.Strings(chars) return strings.Join(chars, "") }