feat(training): 企业培训迭代:核验权限收窄、课程发布状态与培训中心改版

需求域:
- 需求导入修复内/外培训与外部讲师落库;按模板标题年入库(年-月一致)
- 核验确认收窄为「需求归属部门+经理职称角色」,越权提示联系部门经理
- 确认转月计划后自动推送讲师/课长维护;导入后自动推送部门经理核验(站内+企微)

课程域:
- 课程管理发布状态字段(迁移000154)+发布/下线;培训中心「和信课程」目录
- 需求讲师改选后回写课程管理;确认同步带出适合人员/课件/试题
- 月计划详情课件/试题更换(上传/知识库选择/题库换绑)回写课程管理,
  无关联条目的存量计划自动创建课程条目

模板与表单:
- 教育训练需求表:适合人员/内-外培训口径;部门联动课程下拉;
  适合人员/讲师按所选课程自动带出;在线提报课程下拉(本部门)自动带出分类/讲师/适合人员

页面与权限:
- 培训中心页签重组(和信课程/我的培训/我的考试),移除线上/线下页签
- 数据驾驶舱迁侧栏(职称角色之下);职称角色迁至更多工具配置中心之后
- 配置中心/职称角色对经理开放;页签「职称角色」更名「角色权限」
- 修复年度下拉空白(TDesign options 需对象数组)、月计划列表地点兜底

其他: 培训预览端口修正与 dev:training 脚本;tmp-extract-duckdb 加入 gitignore
This commit is contained in:
runny committed 2026-11-19 01:49:17 +08:00
1 parent aae041a0b4
commit 242dd7e1a6
47 files changed
+5882 -1134

No files matched your search

@@ -0,0 +1,27 @@
package repository
import (
"context"
"academy/internal/types/interfaces"
)
// ---------------------------------------------------------------------------
// 培训业务唯一编号(000153)
// 计数器表 tr_code_counters(tenant_id, code_key) 主键UPSERT原子递增,
// key 形如 AP:2026 / MP:202611 / CRS / QB;存量数据由迁移回填并播种计数器。
// ---------------------------------------------------------------------------
// NextCodeValue 返回 code_key 下一个流水值(原子递增,并发安全)。
func (r *trainingRepository) NextCodeValue(ctx context.Context, tenantID uint64, key string) (int64, error) {
var value int64
err := r.db.WithContext(ctx).Raw(`
INSERT INTO tr_code_counters (tenant_id, code_key, value, updated_at)
VALUES (?, ?, 1, CURRENT_TIMESTAMP)
ON CONFLICT (tenant_id, code_key)
DO UPDATE SET value = tr_code_counters.value + 1, updated_at = CURRENT_TIMESTAMP
RETURNING value`, tenantID, key).Scan(&value).Error
return value, err
}
var _ interfaces.TrainingRepository = (*trainingRepository)(nil)
@@ -21,9 +21,9 @@ func (r *trainingRepository) CreateQuestionBank(ctx context.Context, bank *types
// ReplaceQuestionBankByName 同名题库重导入即替换:软删同租户同名旧题库及其全部
// 题目与试卷(含缓存的 ONLINE 自学卷,重导后按新解析重建),返回旧题库的
// 课程关联供新题库继承;无同名旧库时原样返回空串。
func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, error) {
oldCourseID := ""
// 课程/课程管理关联供新题库继承;无同名旧库时原样返回空串。
func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, string, error) {
oldCourseID, oldLibraryCourseID := "", ""
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var banks []*types.TrainingQuestionBank
if err := tx.Where("tenant_id = ? AND name = ? AND deleted_at IS NULL", tenantID, name).
@@ -39,6 +39,9 @@ func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tena
if oldCourseID == "" && b.CourseID != "" {
oldCourseID = b.CourseID
}
if oldLibraryCourseID == "" && b.LibraryCourseID != "" {
oldLibraryCourseID = b.LibraryCourseID
}
}
now := time.Now()
if err := tx.Model(&types.TrainingQuestionBank{}).
@@ -55,7 +58,7 @@ func (r *trainingRepository) ReplaceQuestionBankByName(ctx context.Context, tena
Where("tenant_id = ? AND bank_id IN ?", tenantID, ids).
Update("deleted_at", now).Error
})
return oldCourseID, err
return oldCourseID, oldLibraryCourseID, err
}
// ListQuestionBanks returns a page of question banks.
@@ -110,6 +113,38 @@ func (r *trainingRepository) GetQuestionBankByCourse(ctx context.Context, tenant
return &b, nil
}
// GetQuestionBankByLibraryCourse 取课程管理条目下的题库列表(试题随课程管理维护,
// 000153;updated_at 降序,支持一个课程多个题库)。
func (r *trainingRepository) GetQuestionBankByLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error) {
var banks []*types.TrainingQuestionBank
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND library_course_id = ? AND deleted_at IS NULL", tenantID, libraryCourseID).
Order("updated_at DESC").Find(&banks).Error; err != nil {
return nil, err
}
return banks, nil
}
// DeleteQuestionBank 软删题库及其全部题目与缓存试卷(000153,试题抽屉删除入口)。
func (r *trainingRepository) DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
now := time.Now()
if err := tx.Model(&types.TrainingQuestionBank{}).
Where("tenant_id = ? AND id = ?", tenantID, bankID).
Update("deleted_at", now).Error; err != nil {
return err
}
if err := tx.Model(&types.TrainingQuestion{}).
Where("tenant_id = ? AND bank_id = ?", tenantID, bankID).
Update("deleted_at", now).Error; err != nil {
return err
}
return tx.Model(&types.TrainingPaper{}).
Where("tenant_id = ? AND bank_id = ?", tenantID, bankID).
Update("deleted_at", now).Error
})
}
// GetSelfStudyPaperByBank fetches the bank's course self-study paper
// (无场次、version=ONLINE,与线下场次组卷区分)。
func (r *trainingRepository) GetSelfStudyPaperByBank(ctx context.Context, tenantID uint64, bankID string) (*types.TrainingPaper, error) {
@@ -130,6 +165,22 @@ func (r *trainingRepository) UpdateQuestionBankCourse(ctx context.Context, tenan
Update("course_id", courseID).Error
}
// RelinkQuestionBankToLibraryCourse 更换课程管理条目的试题(000156):先解除该条目
// 下既有题库的挂接,再把所选题库指向该条目(更换即整体替换,其他课程的题库不受影响)。
func (r *trainingRepository) RelinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Model(&types.TrainingQuestionBank{}).
Where("tenant_id = ? AND library_course_id = ? AND id <> ? AND deleted_at IS NULL",
tenantID, libraryCourseID, bankID).
Update("library_course_id", "").Error; err != nil {
return err
}
return tx.Model(&types.TrainingQuestionBank{}).
Where("tenant_id = ? AND id = ? AND deleted_at IS NULL", tenantID, bankID).
Update("library_course_id", libraryCourseID).Error
})
}
// UpdateQuestionBankCount refreshes the denormalized question count.
func (r *trainingRepository) UpdateQuestionBankCount(ctx context.Context, tenantID uint64, bankID string, count int) error {
return r.db.WithContext(ctx).Model(&types.TrainingQuestionBank{}).
@@ -145,6 +196,54 @@ func (r *trainingRepository) BatchCreateQuestions(ctx context.Context, questions
return r.db.WithContext(ctx).Create(&questions).Error
}
// CreateQuestion 插入单题(000153,试题抽屉手工新增)。
func (r *trainingRepository) CreateQuestion(ctx context.Context, question *types.TrainingQuestion) error {
return r.db.WithContext(ctx).Create(question).Error
}
// GetQuestion 取单题。
func (r *trainingRepository) GetQuestion(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestion, error) {
var q types.TrainingQuestion
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).First(&q).Error; err != nil {
return nil, err
}
return &q, nil
}
// UpdateQuestion 更新单题(题干/选项/答案/分值等全字段)。
func (r *trainingRepository) UpdateQuestion(ctx context.Context, question *types.TrainingQuestion) error {
return r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
Where("tenant_id = ? AND id = ?", question.TenantID, question.ID).
Updates(map[string]interface{}{
"seq_no": question.SeqNo,
"type": question.Type,
"stem": question.Stem,
"options": question.Options,
"answer": question.Answer,
"score": question.Score,
"difficulty": question.Difficulty,
"knowledge_point": question.KnowledgePoint,
"analysis": question.Analysis,
}).Error
}
// DeleteQuestion 软删单题(000153,试题抽屉删除入口)。
func (r *trainingRepository) DeleteQuestion(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
Where("tenant_id = ? AND id = ?", tenantID, id).
Update("deleted_at", time.Now()).Error
}
// CountBankQuestions 统计题库现存未删题目数(增删题目后刷新冗余计数)。
func (r *trainingRepository) CountBankQuestions(ctx context.Context, tenantID uint64, bankID string) (int64, error) {
var count int64
err := r.db.WithContext(ctx).Model(&types.TrainingQuestion{}).
Where("tenant_id = ? AND bank_id = ? AND deleted_at IS NULL", tenantID, bankID).
Count(&count).Error
return count, err
}
// ListQuestions returns all questions of a bank ordered by seq_no.
func (r *trainingRepository) ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error) {
var items []*types.TrainingQuestion
@@ -0,0 +1,119 @@
package repository
import (
"context"
"time"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// ---------------------------------------------------------------------------
// 课程管理(课程资产主数据,tr_course_library,000151)。
// 月培训计划的「计划名称」从本表选择,选中后经 tr_courses.library_course_id 关联。
// ---------------------------------------------------------------------------
// ListCourseLibrary returns a page of course-library items with keyword filter
// (分类/类型等前端本地过滤,数据量小全量加载)。
func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
// 列名统一以 tr_course_library 限定:JOIN users 后 tenant_id/updated_at 等
// 同名列不加限定会报 SQLSTATE 42702 歧义(与 ListCourses 同口径)。
tx := r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).Where("tr_course_library.tenant_id = ?", tenantID)
if q != nil {
if q.Keyword != "" {
tx = tx.Where("tr_course_library.name ILIKE ?", "%"+q.Keyword+"%")
}
}
var total int64
if err := tx.Count(&total).Error; err != nil {
return nil, 0, err
}
page, pageSize := 1, 100
if q != nil {
if q.Page > 0 {
page = q.Page
}
if q.PageSize > 0 {
pageSize = q.PageSize
}
}
var items []*types.TrainingCourseLibrary
// lecturer_name 联查真实姓名(讲师可为任意员工,外部讲师直接落姓名列);
// owner_dept_name 联查部门名(所属部门存 org_depts id)。
err := tx.Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
Order("tr_course_library.updated_at DESC").
Offset((page - 1) * pageSize).Limit(pageSize).
Find(&items).Error
return items, total, err
}
// GetCourseLibraryItem fetches one course-library item.
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
var item types.TrainingCourseLibrary
if err := r.db.WithContext(ctx).
Select("tr_course_library.*, COALESCE(NULLIF(lu.display_name, ''), lu.username, '') AS lecturer_name, COALESCE(od.name, '') AS owner_dept_name").
Joins("LEFT JOIN users lu ON lu.id = tr_course_library.lecturer_id").
Joins("LEFT JOIN org_depts od ON od.id = tr_course_library.owner_dept_id AND od.tenant_id = tr_course_library.tenant_id AND od.deleted_at IS NULL").
Where("tr_course_library.tenant_id = ? AND tr_course_library.id = ?", tenantID, id).First(&item).Error; err != nil {
return nil, err
}
return &item, nil
}
// CreateCourseLibraryItem inserts one course-library item.
func (r *trainingRepository) CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error {
return r.db.WithContext(ctx).Create(item).Error
}
// UpdateCourseLibraryItem updates mutable course-library fields (file columns included:
// 课件文件上传后随行更新,清空即置空)。
func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error {
return r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).
Where("tenant_id = ? AND id = ?", item.TenantID, item.ID).
Updates(map[string]interface{}{
"name": item.Name,
"owner_dept_id": item.OwnerDeptID,
"description": item.Description,
"suitable_members": item.SuitableMembers,
"category": item.Category,
"type": item.Type,
"mode": item.Mode,
"lecturer_id": item.LecturerID,
"lecturer_external": item.LecturerExternal,
"hours": item.Hours,
"material_name": item.MaterialName,
"file_key": item.FileKey,
"file_name": item.FileName,
"file_size": item.FileSize,
// 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。
"knowledge_id": item.KnowledgeID,
}).Error
}
// UpdateCourseLibraryPublishStatus 更新课程管理条目发布状态(000154):
// published 已发布 / offline 已下线,供培训中心「和信课程」目录过滤。
func (r *trainingRepository) UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
return r.db.WithContext(ctx).Model(&types.TrainingCourseLibrary{}).
Where("tenant_id = ? AND id = ?", tenantID, id).
Updates(map[string]interface{}{
"publish_status": status,
"updated_at": time.Now(),
}).Error
}
// BatchCreateCourseLibrary inserts course-library items in one batch (Excel 导入)。
func (r *trainingRepository) BatchCreateCourseLibrary(ctx context.Context, items []*types.TrainingCourseLibrary) error {
if len(items) == 0 {
return nil
}
return r.db.WithContext(ctx).Create(&items).Error
}
// DeleteCourseLibraryItem soft-deletes one course-library item.
func (r *trainingRepository) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
Delete(&types.TrainingCourseLibrary{}).Error
}
@@ -69,6 +69,22 @@ func (r *trainingRepository) ListDemands(ctx context.Context, tenantID uint64, q
return items, total, err
}
// ListDemandYears returns distinct demand years of the tenant, latest first
// (年度需求收集页年份下拉数据源:列表中所有计划培训实际年份;
// deptID 非空时收窄到该部门,与纯课长数据范围口径一致)。
func (r *trainingRepository) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) {
var years []int
tx := r.db.WithContext(ctx).Model(&types.TrainingDemand{}).
Where("tenant_id = ? AND year > 0", tenantID)
if deptID != "" {
tx = tx.Where("dept_id = ?", deptID)
}
err := tx.Distinct().
Order("year DESC").
Pluck("year", &years).Error
return years, err
}
// GetDemand fetches one demand.
func (r *trainingRepository) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) {
var d types.TrainingDemand
@@ -375,6 +391,8 @@ func (r *trainingRepository) UpdateCourse(ctx context.Context, course *types.Tra
"session_count": course.SessionCount,
"lecturer_external": course.LecturerExternal,
"remark": course.Remark,
// 课程管理关联(月培训计划「计划名称」来源,000151)。
"library_course_id": course.LibraryCourseID,
}).Error
}
+69 -10
View File
@@ -51,6 +51,62 @@ func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces
func trainingNewID() string { return uuid.New().String() }
// ---------------------------------------------------------------------------
// 唯一编号(000153,前缀+年月+流水,租户内递增)
// 编号计数器失败时 fail-open(记录日志,编号留空),不阻断主流程。
// ---------------------------------------------------------------------------
// nextTrainingCode 经计数器取下一流水并按 format 拼业务编号。
func (s *trainingService) nextTrainingCode(ctx context.Context, tenantID uint64, key string, format func(int64) string) string {
value, err := s.repo.NextCodeValue(ctx, tenantID, key)
if err != nil {
logger.Error(ctx, "Failed to allocate training code", err, "key", key)
return ""
}
return format(value)
}
// nextDemandCode 年计划编号:AP-<year>-####(按年分段)。
func (s *trainingService) nextDemandCode(ctx context.Context, tenantID uint64, year int) string {
return s.nextTrainingCode(ctx, tenantID, fmt.Sprintf("AP:%d", year), func(v int64) string {
return fmt.Sprintf("AP-%d-%04d", year, v)
})
}
// nextMonthPlanCode 月度计划编号:MP-<YYYYMM>-####(按授课月份分段)。
func (s *trainingService) nextMonthPlanCode(ctx context.Context, tenantID uint64, year, month int) string {
key := fmt.Sprintf("MP:%04d%02d", year, month)
return s.nextTrainingCode(ctx, tenantID, key, func(v int64) string {
return fmt.Sprintf("MP-%04d%02d-%04d", year, month, v)
})
}
// nextCourseLibraryCode 课程编号:CRS-####(租户内流水)。
func (s *trainingService) nextCourseLibraryCode(ctx context.Context, tenantID uint64) string {
return s.nextTrainingCode(ctx, tenantID, "CRS", func(v int64) string {
return fmt.Sprintf("CRS-%04d", v)
})
}
// nextQuestionBankCode 试题库编号:QB-####(租户内流水)。
func (s *trainingService) nextQuestionBankCode(ctx context.Context, tenantID uint64) string {
return s.nextTrainingCode(ctx, tenantID, "QB", func(v int64) string {
return fmt.Sprintf("QB-%04d", v)
})
}
// monthPlanYearMonth 从课程授课时间(teach_time,YYYY-MM 或 YYYY-MM-DD HH:mm)
// 提取计划编号分段年月;解析失败回退当前年月。
func monthPlanYearMonth(teachTime string, now time.Time) (int, int) {
if len(teachTime) >= 7 {
var year, month int
if _, err := fmt.Sscanf(teachTime[:7], "%d-%d", &year, &month); err == nil && year > 0 && month >= 1 && month <= 12 {
return year, month
}
}
return now.Year(), int(now.Month())
}
func trainingJSONFromSlice(items []string) types.JSON {
if len(items) == 0 {
return types.JSON([]byte("[]"))
@@ -260,6 +316,11 @@ func (s *trainingService) ListDemands(ctx context.Context, tenantID uint64, q *i
return s.repo.ListDemands(ctx, tenantID, q)
}
// ListDemandYears returns distinct demand years (desc) for the year filter.
func (s *trainingService) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) {
return s.repo.ListDemandYears(ctx, tenantID, deptID)
}
// GetDemand fetches one demand.
func (s *trainingService) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) {
return s.repo.GetDemand(ctx, tenantID, id)
@@ -335,6 +396,7 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
}
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
// 核验状态默认「待核验」:填报/编辑不自动通过,统一由经理核验确认。
msgs := []string{}
if demand.DeptID == "" {
msgs = append(msgs, "未指定部门")
@@ -346,11 +408,7 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
}
demand.CheckMsg += m
}
if len(msgs) == 0 {
demand.CheckStatus = types.TrainingCheckPassed
} else {
demand.CheckStatus = types.TrainingCheckPending
}
demand.CheckStatus = types.TrainingCheckPending
if demand.Status == "" {
demand.Status = types.TrainingDemandSubmitted
}
@@ -358,6 +416,8 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
if demand.ID == "" {
demand.ID = trainingNewID()
demand.TenantID = tenantID
// 年计划编号(AP-<year>-####,创建时生成;计数器失败留空不阻断)。
demand.Code = s.nextDemandCode(ctx, tenantID, demand.Year)
if err := s.repo.CreateDemand(ctx, demand); err != nil {
return nil, err
}
@@ -382,21 +442,20 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
if demands[i].Year <= 0 {
demands[i].Year = time.Now().Year()
}
// 年计划编号(批量导入逐行生成,同年前缀分段递增)。
demands[i].Code = s.nextDemandCode(ctx, tenantID, demands[i].Year)
if demands[i].Status == "" {
demands[i].Status = types.TrainingDemandSubmitted
}
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
msgs := []string{}
if demands[i].DeptID == "" {
msgs = append(msgs, "未指定部门")
}
demands[i].CheckMsg = strings.Join(msgs, ";")
if len(msgs) == 0 {
demands[i].CheckStatus = types.TrainingCheckPassed
} else {
demands[i].CheckStatus = types.TrainingCheckPending
}
demands[i].CheckStatus = types.TrainingCheckPending
}
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
return nil, err
+106 -2
View File
@@ -97,18 +97,114 @@ func courseExamStatus(expected int, st *types.TrainingCourseStudyStats) string {
}
// GetCourse returns one course.
// courseExamBank 课程考试题库解析(000153):优先取课程直连题库(course_id),
// 未绑定时回退课程管理条目下的题库(library_course_id,试题随课程管理维护)。
func (s *trainingService) courseExamBank(ctx context.Context, tenantID uint64, course *types.TrainingCourse) (*types.TrainingQuestionBank, error) {
if course == nil {
return nil, errors.NewNotFoundError("课程不存在")
}
if bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, course.ID); err == nil && bank != nil {
return bank, nil
}
if course.LibraryCourseID == "" {
return nil, errors.NewNotFoundError("题库不存在")
}
banks, err := s.repo.GetQuestionBankByLibraryCourse(ctx, tenantID, course.LibraryCourseID)
if err != nil || len(banks) == 0 {
return nil, errors.NewNotFoundError("题库不存在")
}
return banks[0], nil
}
func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourse, error) {
course, err := s.repo.GetCourse(ctx, tenantID, id)
if err != nil {
return nil, errors.NewNotFoundError("课程不存在")
}
// 绑定题库即具备在线考试条件(详情页随堂考试入口与 exam_enabled 开关并联)。
if bank, bankErr := s.repo.GetQuestionBankByCourse(ctx, tenantID, id); bankErr == nil && bank != nil {
// 绑定题库即具备在线考试条件(详情页随堂考试入口与 exam_enabled 开关并联);
// 课程自身未绑定时回退课程管理条目的题库(000153)。
if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil {
course.ExamReady = true
}
return course, nil
}
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
if course.LibraryCourseID == "" {
return nil
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if err != nil || item == nil {
logger.Error(ctx, "Failed to load library course for plan binding", err, "library_course_id", course.LibraryCourseID)
return nil
}
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖。
course.Name = item.Name
course.Type = item.Type
course.Mode = item.Mode
if item.LecturerID != "" || item.LecturerExternal != "" {
course.LecturerID = item.LecturerID
course.LecturerExternal = item.LecturerExternal
}
if !isCreate {
return item
}
// 预填字段:仅新建时带出,后续学时/学分按月度计划维护口径可调。
if course.Hours <= 0 {
course.Hours = item.Hours
}
if course.Code == "" {
course.Code = item.Code
}
if len(course.DeptIDs) == 0 || string(course.DeptIDs) == "[]" || string(course.DeptIDs) == "null" {
if item.OwnerDeptID != "" {
deptIDs, _ := json.Marshal([]string{item.OwnerDeptID})
course.DeptIDs = types.JSON(deptIDs)
}
}
if course.PostScope == "" {
course.PostScope = item.SuitableMembers
}
return item
}
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
func (s *trainingService) attachLibraryCourseMaterial(ctx context.Context, tenantID uint64, courseID string, item *types.TrainingCourseLibrary, updaterID string) {
if item == nil {
return
}
name := item.FileName
if name == "" {
name = item.MaterialName
}
if name == "" {
return
}
kind := "doc"
if isVideoMaterialFile("", name) {
kind = "video"
}
material := &types.TrainingMaterial{
CourseID: courseID,
Kind: kind,
Name: name,
}
if item.KnowledgeID != "" {
material.KnowledgeID = item.KnowledgeID
} else {
material.FileKey = item.FileKey
}
if _, err := s.CreateMaterial(ctx, tenantID, material, updaterID); err != nil {
logger.Error(ctx, "Failed to attach library course material to plan", err, "course_id", courseID)
}
}
// SaveCourse creates or updates one course.
func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, course *types.TrainingCourse, updaterID string) (*types.TrainingCourse, error) {
if course.Name == "" {
@@ -124,12 +220,20 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
course.ID = trainingNewID()
course.TenantID = tenantID
course.CreatorID = updaterID
// 课程管理信息带出与锁定(000153),课件资料随计划挂接(线上发布/学习页依赖)。
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, true)
s.attachLibraryCourseMaterial(ctx, tenantID, course.ID, libItem, updaterID)
// 月度计划编号(MP-<YYYYMM>-####,按授课月份分段;解析失败取当前月)。
year, month := monthPlanYearMonth(course.TeachTime, time.Now())
course.PlanCode = s.nextMonthPlanCode(ctx, tenantID, year, month)
if err := s.repo.CreateCourse(ctx, course); err != nil {
return nil, err
}
return course, nil
}
course.TenantID = tenantID
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。
s.applyLibraryCourseBinding(ctx, tenantID, course, false)
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
if err != nil {
+120 -11
View File
@@ -42,6 +42,8 @@ func (s *trainingService) ImportQuestionBank(ctx context.Context, tenantID uint6
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
}
@@ -70,7 +72,7 @@ func (s *trainingService) ImportQuestionBank(ctx context.Context, tenantID uint6
// 模板中的「课程名称」列仅作对照展示,题库与课程的关联以导入弹窗选择的课程为准。
// 两种格式均合并解析全部工作表;入库后把原始 Excel 自动同步进系统默认
// 「企业培训(题库)」知识库(fail-open),使题库内容支持 AI 对话问答。
func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error) {
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("缺少上传文件")
}
@@ -88,15 +90,18 @@ func (s *trainingService) ImportQuestionBankExcel(ctx context.Context, tenantID
return nil, err
}
// 同名重导入即替换:清掉旧题库的题目与缓存试卷(坏数据/旧 ONLINE 卷一并失效),
// 调用方未指定归属课程时继承旧题库的课程关联。
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
// 调用方未指定归属课程/课程管理条目时继承旧题库的关联。
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
if err != nil {
return nil, err
}
if courseID == "" {
courseID = oldCourseID
}
bank := &types.TrainingQuestionBank{Name: name, DeptID: deptID, CourseID: courseID}
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)
@@ -135,7 +140,7 @@ func (s *trainingService) parseQuestionBankExcel(ctx context.Context, tenantID u
// ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档直接导入题库:
// 取回 Excel 原件解析建库,文档已在知识库故直接挂接 knowledge_id 不重复上传;
// 未指定归属课程时继承同名旧题库的课程关联。
func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, updaterID string) (*types.TrainingQuestionBank, error) {
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("缺少知识库文档")
}
@@ -156,17 +161,113 @@ func (s *trainingService) ImportQuestionBankFromKnowledge(ctx context.Context, t
if err != nil {
return nil, err
}
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
if err != nil {
return nil, err
}
if courseID == "" {
courseID = oldCourseID
}
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, KnowledgeID: knowledgeID}
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
@@ -855,9 +956,13 @@ const courseSelfStudyPaperVersion = "ONLINE"
// GetCourseExamPaper 线上自学考试入口:确保课程线上卷存在并返回学员视角
// 题目(卷不存在时按题库全量题数现场组卷,幂等)。
func (s *trainingService) GetCourseExamPaper(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingPaper, []*types.TrainingQuestion, error) {
// 绑定题库即默认可答题:只要课程关联了题库就允许取卷答题,
// exam_enabled 仅决定详情页是否主动展示考试入口。
bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, courseID)
// 绑定题库即默认可答题:只要课程(或其课程管理条目,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("该课程未绑定题库,请联系培训管理员在课程管理中关联题库")
}
@@ -878,7 +983,11 @@ func (s *trainingService) GetCourseExamPaper(ctx context.Context, tenantID uint6
// 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) {
bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, courseID)
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
}
@@ -0,0 +1,330 @@
package service
import (
"context"
"fmt"
"io"
"mime/multipart"
"strings"
"time"
excelize "github.com/xuri/excelize/v2"
werrors "academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// ---------------------------------------------------------------------------
// 课程管理(课程资产主数据,tr_course_library,000151)。
// 字段口径:课程名称/所属部门(org_depts)/说明/适合人员/分类(配置中心
// course_category_dict 可配,支持自定义)/类型(必修课/选修课)/线上或线下/
// 讲师/时长/课件(名称登记+可选原始文件)。
// 月培训计划的「计划名称」从本表选择,计划创建经 library_course_id 关联。
// ---------------------------------------------------------------------------
// courseLibraryTypeLabel 类型展示文案(导出用)。
func courseLibraryTypeLabel(t string) string {
if t == "elective" {
return "选修课"
}
return "必修课"
}
// courseLibraryModeLabel 形式展示文案(导出用)。
func courseLibraryModeLabel(m string) string {
if m == types.TrainingCourseModeOnline {
return "线上"
}
return "线下"
}
// normalizeCourseLibrary 归一保存/导入共用的字段口径(名称必填、类型/形式白名单)。
func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
item.Name = strings.TrimSpace(item.Name)
if item.Name == "" {
return werrors.NewBadRequestError("课程名称不能为空")
}
item.OwnerDeptID = strings.TrimSpace(item.OwnerDeptID)
item.Category = strings.TrimSpace(item.Category)
item.Description = strings.TrimSpace(item.Description)
item.SuitableMembers = strings.TrimSpace(item.SuitableMembers)
item.LecturerID = strings.TrimSpace(item.LecturerID)
item.LecturerExternal = strings.TrimSpace(item.LecturerExternal)
item.MaterialName = strings.TrimSpace(item.MaterialName)
if item.Type != "elective" {
item.Type = "required"
}
if item.Mode != types.TrainingCourseModeOnline {
item.Mode = types.TrainingCourseModeOffline
}
return nil
}
// ListCourseLibraryItems 课程管理列表(月培训计划「计划名称」下拉同源)。
func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
return s.repo.ListCourseLibrary(ctx, tenantID, q)
}
// SaveCourseLibraryItem 新增/编辑课程管理条目(id 空 = 新增)。
func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error) {
if err := normalizeCourseLibrary(item); err != nil {
return nil, err
}
if item.ID == "" {
item.ID = trainingNewID()
item.TenantID = tenantID
item.CreatorID = updaterID
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
return item, nil
}
// 编辑:先取旧值校验存在性,再全量更新(文件字段随行透传,未动即保持原值)。
old, err := s.repo.GetCourseLibraryItem(ctx, tenantID, item.ID)
if err != nil || old == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
// 课件文件:移除标记强制清空;未重新上传时保留原文件信息
// (表单不回传 file_key,零值会被误清)。
if item.ClearFile {
item.FileKey, item.FileName, item.FileSize = "", "", 0
item.KnowledgeID = ""
} else if item.FileKey == "" && item.FileName == "" && item.FileSize == 0 {
item.FileKey, item.FileName, item.FileSize = old.FileKey, old.FileName, old.FileSize
}
// 知识库文档 id 不随表单回传:未重新上传时保留原值(与新文件一并覆盖)。
if item.KnowledgeID == "" {
item.KnowledgeID = old.KnowledgeID
}
item.TenantID = tenantID
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
return item, nil
}
// DeleteCourseLibraryItem 软删课程管理条目(月培训计划已创建的历史计划不受影响)。
func (s *trainingService) DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error {
if _, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id); err != nil {
return werrors.NewNotFoundError("课程不存在")
}
return s.repo.DeleteCourseLibraryItem(ctx, tenantID, id)
}
// GetCourseLibraryItem 取单条课程管理条目(发布/下线等操作后回显)。
func (s *trainingService) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
return item, nil
}
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154):published 已发布 /
// offline 已下线;培训中心「和信课程」目录仅展示已发布课程。
func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error {
if status != "published" && status != "offline" {
return werrors.NewBadRequestError("发布状态不合法(仅支持发布/下线)")
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
return werrors.NewNotFoundError("课程不存在")
}
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
}
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {
if len(items) == 0 {
return 0, werrors.NewBadRequestError("没有可导入的课程数据")
}
rows := make([]*types.TrainingCourseLibrary, 0, len(items))
for _, item := range items {
if err := normalizeCourseLibrary(item); err != nil {
continue // 缺课程名称的行跳过(前端同步提示跳过行数)
}
item.ID = trainingNewID()
item.TenantID = tenantID
item.CreatorID = updaterID
// 课程编号逐行生成(CRS-####)。
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
rows = append(rows, item)
}
if len(rows) == 0 {
return 0, werrors.NewBadRequestError("没有可导入的课程数据(未填课程名称的行已跳过)")
}
if err := s.repo.BatchCreateCourseLibrary(ctx, rows); err != nil {
return 0, err
}
logger.Infof(ctx, "[Training] course library imported, tenant=%d rows=%d importer=%s", tenantID, len(rows), updaterID)
return len(rows), nil
}
// ExportCourseLibrary 导出课程管理 Excel(ids 空 = 全量;当前筛选由前端传 ids)。
func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (string, []byte, error) {
items, _, err := s.repo.ListCourseLibrary(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 5000})
if err != nil {
return "", nil, err
}
if len(ids) > 0 {
keep := make(map[string]bool, len(ids))
for _, id := range ids {
keep[id] = true
}
filtered := items[:0]
for _, item := range items {
if keep[item.ID] {
filtered = append(filtered, item)
}
}
items = filtered
}
f := excelize.NewFile()
sheet := "课程管理"
f.SetSheetName("Sheet1", sheet)
// 列口径对齐《教育训练需求表》:所属部门=主办单位,适合人员=参加人员,
// 课件=课件收集;导入解析端(LibraryPanel onImportExcel)两套列名均兼容。
headers := []string{"课程编号", "所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
"类型", "线上/线下", "讲师", "时长(学时)", "课件收集", "创建时间"}
for i, h := range headers {
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
_ = f.SetCellValue(sheet, cell, h)
}
hoursText := func(h float64) string {
if h == 0 {
return ""
}
return fmt.Sprintf("%g", h)
}
for r, item := range items {
lecturer := item.LecturerName
if lecturer == "" {
lecturer = item.LecturerExternal
}
values := []string{item.Code, item.OwnerDeptName, item.Name, item.Description, item.SuitableMembers, item.Category,
courseLibraryTypeLabel(item.Type), courseLibraryModeLabel(item.Mode),
lecturer, hoursText(item.Hours), item.MaterialName, item.CreatedAt.Format("2006-01-02 15:04")}
for i, v := range values {
cell, _ := excelize.CoordinatesToCellName(i+1, r+2)
_ = f.SetCellValue(sheet, cell, v)
}
}
buf, err := f.WriteToBuffer()
if err != nil {
return "", nil, err
}
filename := fmt.Sprintf("course_library_%s.xlsx", time.Now().Format("20060102150405"))
logger.Infof(ctx, "[Training] course library exported, tenant=%d rows=%d", tenantID, len(items))
return filename, buf.Bytes(), nil
}
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key,不入知识库
// 解析链路;名称登记与文件可并存)。
func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error) {
if fh == nil {
return nil, werrors.NewBadRequestError("缺少上传文件")
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
fileKey, err := s.fileSvc.SaveFile(ctx, fh, tenantID, "")
if err != nil {
logger.Errorf(ctx, "Failed to save course library material, error: %v", err)
return nil, err
}
item.FileKey = fileKey
item.FileName = fh.Filename
item.FileSize = fh.Size
// 文档类课件同步知识库「企业培训(课件)」(000153:AI 出题与对话问答依赖
// 知识库分块;视频类仍只存原始文件)。同步失败 fail-open,退回原始文件存取。
if !isVideoMaterialFile("", fh.Filename) {
coursewareKB, _, kbErr := s.ensureTrainingKnowledgeBases(ctx)
if kbErr != nil {
logger.Warnf(ctx, "Skip syncing course library material to knowledge base (ensure failed): %v", kbErr)
} else if knowledgeID, syncErr := s.syncFileToKnowledgeBase(ctx, coursewareKB.ID, fh, ""); syncErr != nil {
logger.Warnf(ctx, "Skip syncing course library material to knowledge base (upload failed): %v", syncErr)
} else {
item.KnowledgeID = knowledgeID
}
} else {
item.KnowledgeID = ""
}
// 名称登记为空时以文件名兜底,便于列表直接识别课件。
if strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = fh.Filename
}
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
logger.Infof(ctx, "[Training] course library material uploaded, tenant=%d course=%s size=%d uploader=%s", tenantID, id, fh.Size, updaterID)
return item, nil
}
// GetCourseLibraryMaterialFile 流式取回课件原始文件:文档类优先按知识库文档
// 取回流(000153 同步入库后与月计划课件同口径),视频/同步失败回退 file_key。
func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error) {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
return nil, "", werrors.NewNotFoundError("课程不存在")
}
if item.FileKey == "" && item.KnowledgeID == "" {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
}
if item.KnowledgeID != "" {
rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, item.KnowledgeID)
if err == nil {
// 下载文件名沿用登记名(知识库文档名可能与登记名不一致)。
return rc, item.FileName, nil
}
logger.Warnf(ctx, "Fallback to raw file for course library material, course: %s, error: %v", id, err)
}
if item.FileKey == "" {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
}
rc, err := s.fileSvc.GetFile(ctx, item.FileKey)
if err != nil {
return nil, "", err
}
return rc, item.FileName, nil
}
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
// 原始文件字段清空,名称登记为空时以文档名兜底。
func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error) {
knowledgeID = strings.TrimSpace(knowledgeID)
if knowledgeID == "" {
return nil, werrors.NewBadRequestError("缺少知识库文档")
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
doc, docErr := s.knowledgeSvc.GetKnowledgeByID(ctx, knowledgeID)
if docErr != nil || doc == nil {
return nil, werrors.NewNotFoundError("知识库文档不存在")
}
name := strings.TrimSpace(doc.FileName)
if name == "" {
name = strings.TrimSpace(doc.Title)
}
if name != "" {
item.FileName = name
if strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = name
}
}
item.FileKey, item.FileSize = "", 0
item.KnowledgeID = knowledgeID
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
logger.Infof(ctx, "[Training] course library material attached from knowledge base, tenant=%d course=%s knowledge=%s operator=%s", tenantID, id, knowledgeID, updaterID)
return item, nil
}
@@ -171,6 +171,9 @@ 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}`,
@@ -179,6 +182,7 @@ func defaultRuleSeed() map[string]string {
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}`,
@@ -46,12 +46,6 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
if s.chunkSvc == nil || s.models == nil {
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
}
if count <= 0 {
count = 10
}
if count > 30 {
count = 30
}
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
if err != nil || material == nil {
return nil, errors.NewNotFoundError("课件不存在")
@@ -62,21 +56,50 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
if material.KnowledgeID == "" {
return nil, errors.NewBadRequestError("该课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
}
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, material.KnowledgeID, material.Name, count)
}
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(000153):读取课程管理
// 条目课件同步知识库后的分块文本出题;题目不落库,预览确认后经
// ImportGeneratedQuestionBank 建库并挂 library_course_id。
func (s *trainingService) GenerateLibraryCourseQuestions(ctx context.Context, tenantID uint64, userID, libraryCourseID string, count int) ([]*types.TrainingQuestion, error) {
if s.chunkSvc == nil || s.models == nil {
return nil, errors.NewBadRequestError("AI 能力未就绪(缺少分块/模型服务)")
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, libraryCourseID)
if err != nil || item == nil {
return nil, errors.NewNotFoundError("课程不存在")
}
if item.KnowledgeID == "" {
return nil, errors.NewBadRequestError("该课程课件未同步知识库,无法 AI 生成试题(请重新上传课件)")
}
return s.generateQuestionsFromKnowledge(ctx, tenantID, userID, item.KnowledgeID, item.Name, count)
}
// generateQuestionsFromKnowledge 按知识库文档分块拼上下文并交默认模型出题
// (GenerateCourseQuestions / GenerateLibraryCourseQuestions 共用管线)。
func (s *trainingService) generateQuestionsFromKnowledge(ctx context.Context, tenantID uint64, userID, knowledgeID, sourceName string, count int) ([]*types.TrainingQuestion, error) {
if count <= 0 {
count = 10
}
if count > 30 {
count = 30
}
// 拼接课件的知识库文本分块,截断到 ~12k 字符控制 token。
// 兜底:knowledge_id 悬空(知识库文档被删除/重建导致引用失效)时,
// 按课件名在「企业培训(课件)」知识库找同名文档取分块,避免旧引用卡死出题。
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, material.KnowledgeID)
chunks, chunkErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, knowledgeID)
if chunkErr != nil || len(chunks) == 0 {
if altID := s.findCoursewareKnowledgeIDByName(ctx, material.Name); altID != "" {
if altID := s.findCoursewareKnowledgeIDByName(ctx, sourceName); altID != "" {
if altChunks, altErr := s.chunkSvc.ListChunksByKnowledgeID(ctx, altID); altErr == nil && len(altChunks) > 0 {
material.KnowledgeID = altID
knowledgeID = altID
chunks = altChunks
}
}
}
if len(chunks) == 0 {
return nil, errors.NewBadRequestError(
"课件文本索引缺失(知识库分块已被清理),请在知识库中对该文档「重新解析」,或在课程详情重新上传课件后再试")
"课件文本索引缺失(知识库分块已被清理),请在知识库中对该文档「重新解析」,或重新上传课件后再试")
}
var sb strings.Builder
for _, c := range chunks {
@@ -100,7 +123,7 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
}
llmCtx, cancel := context.WithTimeout(ctx, aiQuestionGenTimeout)
defer cancel()
llmCtx = types.WithLLMCallMetadata(llmCtx, "training.course_question_gen", material.KnowledgeID)
llmCtx = types.WithLLMCallMetadata(llmCtx, "training.course_question_gen", knowledgeID)
thinking := false
response, err := model.Chat(llmCtx, []chat.Message{
{Role: "system", Content: aiQuestionSystemPrompt()},
@@ -114,7 +137,7 @@ func (s *trainingService) GenerateCourseQuestions(ctx context.Context, tenantID
logger.Warnf(ctx, "[training] ai question gen llm call failed: %v", err)
return nil, errors.NewBadRequestError("大模型调用失败:" + aiErrBrief(err))
}
return parseAIQuestions(response.Content, material.Name)
return parseAIQuestions(response.Content, sourceName)
}
// findCoursewareKnowledgeIDByName 在「企业培训(课件)」知识库按标题/文件名
@@ -212,9 +235,9 @@ func extractJSONBracket(content string, open, close byte) string {
}
// ImportGeneratedQuestionBank 使用(AI 生成并经人工编辑的)题目建题库:
// 关联课程;题目以分节文本同步进「企业培训(题库)」知识库(检索与 AI 问答可用);
// 未指定课程时继承同名旧题库的课程关联,同名旧库会被替换。
func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) {
// 关联课程/课程管理条目;题目以分节文本同步进「企业培训(题库)」知识库(检索与
// AI 问答可用);未指定归属时继承同名旧题库的关联,同名旧库会被替换。
func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, libraryCourseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error) {
if len(questions) == 0 {
return nil, errors.NewBadRequestError("题目为空")
}
@@ -222,15 +245,18 @@ func (s *trainingService) ImportGeneratedQuestionBank(ctx context.Context, tenan
if name == "" {
name = "AI生成题库"
}
oldCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
oldCourseID, oldLibraryCourseID, err := s.repo.ReplaceQuestionBankByName(ctx, tenantID, name)
if err != nil {
return nil, err
}
if courseID == "" {
courseID = oldCourseID
}
if libraryCourseID == "" {
libraryCourseID = oldLibraryCourseID
}
knowledgeID := s.syncQuestionsToBankKB(ctx, questions, name)
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, KnowledgeID: knowledgeID}
bank := &types.TrainingQuestionBank{Name: name, CourseID: courseID, LibraryCourseID: libraryCourseID, KnowledgeID: knowledgeID}
return s.ImportQuestionBank(ctx, tenantID, bank, questions, updaterID)
}
+330 -33
View File
@@ -3,21 +3,26 @@ package service
import (
"bytes"
"context"
"encoding/json"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"time"
"academy/internal/assets/trainingtemplates"
"academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/xuri/excelize/v2"
)
// ---------------------------------------------------------------------------
// 配置中心 · 导入模板管理:
// 模板按业务键(demand_collection/question_bank)管理,租户上传的自定义版本存
// tr_templates 并全端生效;未上传或「恢复默认」后下载回退二进制内置文件
// (internal/assets/trainingtemplates,源 docs/moban)。
// 模板按业务键(demand_collection/question_bank/course_library)管理,租户上传的
// 自定义版本存 tr_templates 并全端生效;未上传或「恢复默认」后下载回退二进制
// 内置文件(internal/assets/trainingtemplates,源 docs/moban)。
// ---------------------------------------------------------------------------
// templateMaxSize 模板 Excel 上限(10MB,业务模板均为几十 KB 级,防误传大文件)。
@@ -26,19 +31,21 @@ const templateMaxSize = 10 << 20
// ListTrainingTemplates returns metadata of all managed templates,
// merging tenant custom versions over bundled defaults.
func (s *trainingService) ListTrainingTemplates(ctx context.Context, tenantID uint64) ([]*types.TrainingTemplateMeta, error) {
keys := []string{
types.TrainingTemplateDemandCollection,
types.TrainingTemplateQuestionBank,
types.TrainingTemplateCourseLibrary,
}
customs := map[string]*types.TrainingTemplate{}
if tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, types.TrainingTemplateDemandCollection); err != nil {
return nil, err
} else if tpl != nil {
customs[tpl.TemplateKey] = tpl
for _, key := range keys {
tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, key)
if err != nil {
return nil, err
}
if tpl != nil {
customs[tpl.TemplateKey] = tpl
}
}
if tpl, err := s.repo.GetTrainingTemplate(ctx, tenantID, types.TrainingTemplateQuestionBank); err != nil {
return nil, err
} else if tpl != nil {
customs[tpl.TemplateKey] = tpl
}
keys := []string{types.TrainingTemplateDemandCollection, types.TrainingTemplateQuestionBank}
out := make([]*types.TrainingTemplateMeta, 0, len(keys))
for _, key := range keys {
meta := &types.TrainingTemplateMeta{
@@ -65,7 +72,8 @@ func (s *trainingService) ListTrainingTemplates(ctx context.Context, tenantID ui
// TrainingTemplateFile resolves the effective template bytes:
// tenant custom version first, bundled default otherwise.
// 收集模板(demand_collection)在返回前注入组织架构下拉(见 enrichDemandTemplate)。
// 收集模板(demand_collection)在返回前动态注入下拉与年份(见 enrichDemandTemplate);
// 课程管理模板(course_library)在返回前动态注入下拉(见 enrichCourseLibraryTemplate)。
func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uint64, key string) ([]byte, string, error) {
if !trainingtemplates.IsKnown(key) {
return nil, "", errors.NewBadRequestError("未知模板类型")
@@ -86,8 +94,11 @@ func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uin
return nil, "", errors.NewBadRequestError("模板文件缺失")
}
}
if key == types.TrainingTemplateDemandCollection {
switch key {
case types.TrainingTemplateDemandCollection:
data = s.enrichDemandTemplate(ctx, tenantID, data)
case types.TrainingTemplateCourseLibrary:
data = s.enrichCourseLibraryTemplate(ctx, tenantID, data)
}
return data, fileName, nil
}
@@ -95,21 +106,38 @@ func (s *trainingService) TrainingTemplateFile(ctx context.Context, tenantID uin
// demandTemplateOptionCols 收集模板下拉辅助列(明细表内右侧隐藏列,
// 同表引用规避跨表公式与 255 字符内联列表限制)。
const (
demandOptColDept = "CA" // 部门单位(组织架构部门)
demandOptColJoin = "CB" // 参加人员(员工档案)
demandOptColLect = "CC" // 培训讲师(员工档案)
demandTargetRows = 500 // 下拉覆盖的数据行数(第 4~503 行)
demandMemberLimit = 2000 // 员工档案下拉取值上限
demandOptColDept = "CA" // 部门单位(组织架构部门)
demandOptColLect = "CC" // 培训讲师(员工档案)
// 课程联动查找表(000156):CE=课程名称 CF=所属部门 CG=适合人员 CH=讲师,
// 按部门分组排序;C 列下拉经 OFFSET+MATCH 联动 B 列所选部门,D/I 列
// VLOOKUP 自动带出该课程的适合人员/讲师(可改写,改后按填写值导入)。
demandLookupColName = "CE"
demandLookupColDept = "CF"
demandLookupColSuit = "CG"
demandLookupColLect = "CH"
demandTargetRows = 500 // 下拉覆盖的数据行数(第 4~503 行)
demandMemberLimit = 2000 // 员工档案下拉取值上限
demandCourseLimit = 2000 // 课程管理下拉取值上限
)
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)注入
// 组织架构下拉:
// - 「部门」(B 列)下拉=组织架构部门;
// - 「参加人员」(D 列)「讲师」(I 列)下拉=员工档案人员姓名(联查 users 优先取
// display_name 真实姓名,回退 username 工号;去重去空);
// demandTitleYearRe 标题行年份(如「2026 年 度 教 育 训 练 需 求 表」)。
var demandTitleYearRe = regexp.MustCompile(`20\d{2}`)
// enrichDemandTemplate 给教育训练需求表模板(内置默认/自定义 xlsx 版)动态注入:
// - 标题年份改为下一年度(收集模板面向下年度计划,如 2026 年下载即 2027);
// - 「计划培训时间」(H 列)表头改为「计划培训月份」,下拉=1~12 月;
// - 「参加人员」(D 列)表头归一为「适合人员」(000154 新口径,兼容旧自定义模板);
// - 「內/外培訓」(G 列)表头归一为「内/外培训」,下拉=内部/外部;
// - 「课程名称」(C 列)下拉按 B 列所选部门联动(OFFSET+MATCH 引用课程查找表,
// 仅列该部门课程;非阻断式,也可直接填写新课程);
// - 「适合人员」(D 列)「讲师」(I 列)按所选课程 VLOOKUP 自动带出(可改写,
// 改后按填写值导入);I 列同时保留员工档案人员下拉;
// - 「部门」(B 列)下拉=组织架构部门;「讲师」(I 列)下拉=员工档案人员姓名
// (联查 users 优先取 display_name 真实姓名,回退 username 工号;去重去空)。
//
// 取值写入同表隐藏辅助列(CA/CB/CC),以数据验证下拉呈现(数据区 4~503 行)。
// 基础文件不可解析(如旧 .xls 自定义版)或数据源失败时原样返回,不阻断下载。
// 取值写入同表隐藏辅助列(CA/CC + 课程查找表 CE~CH),以数据验证/公式呈现
// (数据区 4~503 行)。基础文件不可解析(如旧 .xls 自定义版)或数据源失败时
// 原样返回,不阻断下载。
func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uint64, base []byte) []byte {
f, err := excelize.OpenReader(bytes.NewReader(base))
if err != nil {
@@ -121,7 +149,33 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
}
sheet := sheets[0]
// 下拉取值:组织架构部门 + 员工档案人员(去重、去空)
// 标题年份:面向下一年度收集(2026 年打开即 2027 年度教育训练需求表)。
// 标题合并于 B1:J1(值存左上角),扫描首行 A1:J1 兼容自定义版式差异。
nextYear := time.Now().Year() + 1
for _, col := range []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"} {
val, _ := f.GetCellValue(sheet, col+"1")
if demandTitleYearRe.MatchString(val) {
_ = f.SetCellValue(sheet, col+"1",
demandTitleYearRe.ReplaceAllString(val, strconv.Itoa(nextYear)))
break
}
}
// 「计划培训时间」表头改「计划培训月份」(H2 合并单元格左上角取值)。
if val, _ := f.GetCellValue(sheet, "H2"); strings.Contains(val, "计划培训时间") {
_ = f.SetCellValue(sheet, "H2", "计划培训月份")
}
// 表头归一(000154,兼容旧版自定义模板):「参加人员」D2 → 「适合人员」,
// 「內/外培訓」G2 → 「内/外培训」(繁体转简体+新文案)。
if val, _ := f.GetCellValue(sheet, "D2"); strings.Contains(val, "参加人员") {
_ = f.SetCellValue(sheet, "D2", "适合人员")
}
if val, _ := f.GetCellValue(sheet, "G2"); strings.Contains(val, "培訓") || strings.Contains(val, "培训") {
_ = f.SetCellValue(sheet, "G2", "内/外培训")
}
// 下拉取值:组织架构部门 + 课程管理课程 + 员工档案人员(去重、去空)
deptNames := []string{}
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
@@ -130,6 +184,37 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
}
}
}
// 课程联动查找表(000156):按部门分组排序后写隐藏列 CE~CH,
// 供 C 列部门联动下拉(OFFSET+MATCH)与 D/I 列自动带出(VLOOKUP)引用。
type demandCourseRow struct{ name, dept, suitable, lecturer string }
courseRows := []demandCourseRow{}
if courses, _, err := s.repo.ListCourseLibrary(ctx, tenantID, &interfaces.TrainingListQuery{
Page: 1, PageSize: demandCourseLimit,
}); err == nil {
for _, c := range courses {
if c == nil || strings.TrimSpace(c.Name) == "" {
continue
}
courseRows = append(courseRows, demandCourseRow{
name: strings.TrimSpace(c.Name),
dept: strings.TrimSpace(c.OwnerDeptName),
suitable: strings.TrimSpace(c.SuitableMembers),
lecturer: strings.TrimSpace(c.LecturerName),
})
}
sort.SliceStable(courseRows, func(i, j int) bool {
// 部门升序分组(未挂部门的排最后),同部门按课程名升序:
// OFFSET+COUNTIF 联动公式要求同部门课程在查找表中连续。
di, dj := courseRows[i].dept, courseRows[j].dept
if (di == "") != (dj == "") {
return di != ""
}
if di != dj {
return di < dj
}
return courseRows[i].name < courseRows[j].name
})
}
empNames := []string{}
if members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, &types.OrgListQuery{
Page: 1, PageSize: demandMemberLimit,
@@ -148,10 +233,19 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
}
}
// 「适合人员」(D 列)不挂下拉(改由 VLOOKUP 自动带出,可改写);清除既有验证
// (含历史版本注入的),避免叠加。
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("D4:D%d", demandTargetRows+3))
// 「内/外培训」(G 列)先清既有验证再挂固定下拉,避免旧版模板叠加重复下拉。
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("G4:G%d", demandTargetRows+3))
// 「课程名称」(C 列)清既有验证(历史版本注入过扁平课程下拉),换部门联动下拉。
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("C4:C%d", demandTargetRows+3))
// 写隐藏辅助列并以数据验证下拉挂到对应列。
// 下拉为非阻断式(ShowErrorMessage=false,NewDataValidation 默认):单元格可
// 自由填写——参加人员可填多人(、/,分隔),讲师可填系统外姓名。
// prompt 为选中单元格时浮出的输入提示,引导多选与外部讲师填写方式。
// 自由填写——课程名称可选可填新课程,讲师可填系统外姓名。
// prompt 为选中单元格时浮出的输入提示,引导填写方式。
applyList := func(optCol, header string, values []string, targetRange string, prompt string) {
if len(values) == 0 {
return
@@ -176,11 +270,72 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
_ = f.AddDataValidation(sheet, dv)
}
applyList(demandOptColDept, "部门(组织架构)", deptNames, fmt.Sprintf("B4:B%d", demandTargetRows+3), "")
applyList(demandOptColJoin, "参加人员(员工档案)", empNames,
fmt.Sprintf("D4:D%d", demandTargetRows+3), "可从下拉选择,也可直接填写多个姓名,用、或,分隔")
applyList(demandOptColLect, "培训讲师(员工档案)", empNames,
fmt.Sprintf("I4:I%d", demandTargetRows+3), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
// 课程联动(000156):查找表写 CE~CH 隐藏列后——
// C 列下拉 = OFFSET+MATCH 按 B 列所选部门联动该部门课程(同部门课程连续分组);
// D 列 = VLOOKUP 带出课程「适合人员」,I 列 = 带出「讲师」;单元格可改写,
// 改写后按填写值导入(导入解析取单元格显示值)。
if n := len(courseRows); n > 0 {
last := n + 1 // 查找表数据末行(表头占第 1 行)
lookupCols := []string{demandLookupColName, demandLookupColDept, demandLookupColSuit, demandLookupColLect}
headers := []string{"课程名称(课程管理)", "所属部门", "适合人员", "讲师"}
for ci, col := range lookupCols {
if err := f.SetCellValue(sheet, col+"1", headers[ci]); err != nil {
continue
}
}
for i, row := range courseRows {
r := i + 2
vals := []string{row.name, row.dept, row.suitable, row.lecturer}
for ci, col := range lookupCols {
_ = f.SetCellValue(sheet, fmt.Sprintf("%s%d", col, r), vals[ci])
}
}
for _, col := range lookupCols {
_ = f.SetColVisible(sheet, col, false)
}
// C 列部门联动下拉:OFFSET 自 CE2 偏移 MATCH(B4) 行,高度=COUNTIF 该部门课程数。
dvCourse := excelize.NewDataValidation(true)
dvCourse.SetSqref(fmt.Sprintf("C4:C%d", demandTargetRows+3))
dvCourse.Type = "list"
dvCourse.Formula1 = fmt.Sprintf(
"OFFSET($%s$2,MATCH($B4,$%s$2:$%s$%d,0)-1,0,COUNTIF($%s$2:$%s$%d,$B4),1)",
demandLookupColName,
demandLookupColDept, demandLookupColDept, last,
demandLookupColDept, demandLookupColDept, last,
)
dvCourse.SetInput("课程名称(按部门联动)", "先选部门,课程名称下拉即列出该部门课程;也可直接填写新课程")
_ = f.AddDataValidation(sheet, dvCourse)
// D/I 列自动带出:选中课程后显示该课程的适合人员/讲师,可手动改写。
for i := 0; i < demandTargetRows; i++ {
r := i + 4
_ = f.SetCellFormula(sheet, fmt.Sprintf("D%d", r),
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,3,0),""))`,
r, r, demandLookupColName, demandLookupColLect, last))
_ = f.SetCellFormula(sheet, fmt.Sprintf("I%d", r),
fmt.Sprintf(`IF($C%d="","",IFERROR(VLOOKUP($C%d,$%s$2:$%s$%d,4,0),""))`,
r, r, demandLookupColName, demandLookupColLect, last))
}
}
// 「计划培训月份」(H 列)下拉=1~12(内联列表,非阻断式可自由填写)。
dv := excelize.NewDataValidation(true)
dv.SetSqref(fmt.Sprintf("H4:H%d", demandTargetRows+3))
dv.Type = "list"
dv.Formula1 = `"1,2,3,4,5,6,7,8,9,10,11,12"`
dv.SetInput("计划培训月份", "从下拉选择 1~12 月;导入后自动按「标题年份-月份」入库(如 2027-1)")
_ = f.AddDataValidation(sheet, dv)
// 「内/外培训」(G 列)下拉=内部/外部(内联列表,非阻断式可自由填写,留空未选择)。
dvTrain := excelize.NewDataValidation(true)
dvTrain.SetSqref(fmt.Sprintf("G4:G%d", demandTargetRows+3))
dvTrain.Type = "list"
dvTrain.Formula1 = `"内部,外部"`
dvTrain.SetInput("内/外培训", "从下拉选择内部或外部;留空视为未选择")
_ = f.AddDataValidation(sheet, dvTrain)
buf, err := f.WriteToBuffer()
if err != nil {
return base
@@ -188,6 +343,148 @@ func (s *trainingService) enrichDemandTemplate(ctx context.Context, tenantID uin
return buf.Bytes()
}
// courseLibraryTemplateOptionCols 课程管理模板下拉辅助列(同表右侧隐藏列,
// 引用同表规避跨表公式;分类/部门名单可能超过内联列表 255 字符限制故走辅助列)。
const (
courseLibOptColDept = "CA" // 所属部门(组织架构部门)
courseLibOptColCat = "CB" // 课程分类(配置中心字典)
courseLibOptColLect = "CC" // 讲师(员工档案)
courseLibTargetRows = 500 // 下拉覆盖的数据行数(表头在第 1 行,数据区 2~501 行)
courseLibMemberLimit = 2000 // 员工档案下拉取值上限
)
// enrichCourseLibraryTemplate 给课程管理导入模板(内置默认/自定义 xlsx 版)动态注入
// 下拉选择(表头在第 1 行):
// - 「所属部门」(A 列)下拉=组织架构部门;「课程分类」(E 列)下拉=配置中心
// course_category_dict 字典(缺省回退内置 6 类);「讲师」(H 列)下拉=员工档案
// 人员姓名(非阻断式,可直接输入外部讲师姓名);
// - 「类型」(F 列)「线上或线下」(G 列)「课件收集」(J 列)内联列表下拉
// (必修课/选修课、线上/线下、已有课件/暂无课件)。
//
// 全部下拉为非阻断式(ShowErrorMessage=false):下拉建议 + 可自由填写。
// 基础文件不可解析(如旧 .xls 自定义版)时原样返回,不阻断下载。
func (s *trainingService) enrichCourseLibraryTemplate(ctx context.Context, tenantID uint64, base []byte) []byte {
f, err := excelize.OpenReader(bytes.NewReader(base))
if err != nil {
return base
}
sheets := f.GetSheetList()
if len(sheets) == 0 {
return base
}
sheet := sheets[0]
// 下拉取值:组织架构部门 + 课程分类字典 + 员工档案人员(去重、去空)
deptNames := []string{}
if depts, err := s.org.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
if d != nil && strings.TrimSpace(d.Name) != "" {
deptNames = append(deptNames, strings.TrimSpace(d.Name))
}
}
}
categories := s.courseCategoryOptions(ctx, tenantID)
empNames := []string{}
if members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, &types.OrgListQuery{
Page: 1, PageSize: courseLibMemberLimit,
}); err == nil {
seen := map[string]bool{}
for _, m := range members {
if m == nil {
continue
}
name := strings.TrimSpace(m.UserName)
if name == "" || seen[name] {
continue
}
seen[name] = true
empNames = append(empNames, name)
}
}
applyCourseLibraryDropdowns(f, sheet, deptNames, categories, empNames)
buf, err := f.WriteToBuffer()
if err != nil {
return base
}
return buf.Bytes()
}
// courseCategoryOptions 读取课程分类字典(tr_rule_configs course_category_dict;
// 未配置或损坏时回退内置默认分类,与前端 fetchCourseCategories 同口径)。
func (s *trainingService) courseCategoryOptions(ctx context.Context, tenantID uint64) []string {
if cfg, err := s.repo.GetRuleConfig(ctx, tenantID, types.RuleKeyCourseCategoryDict); err == nil && cfg != nil && len(cfg.RuleValue) > 0 {
var raw struct {
Categories []string `json:"categories"`
}
if err := json.Unmarshal(cfg.RuleValue, &raw); err == nil {
out := make([]string, 0, len(raw.Categories))
for _, c := range raw.Categories {
if v := strings.TrimSpace(c); v != "" {
out = append(out, v)
}
}
if len(out) > 0 {
return out
}
}
}
return types.DefaultCourseCategories()
}
// applyCourseLibraryDropdowns 课程管理模板下拉注入(纯 xlsx 操作,便于单测):
// 动态选项(部门/分类/讲师)写同表隐藏辅助列后以数据验证引用;固定选项
// (类型/线上或线下/课件收集)用内联列表;全部非阻断式,可选可自由填写。
func applyCourseLibraryDropdowns(f *excelize.File, sheet string, deptNames, categories, empNames []string) {
// 先清目标列既有验证(兼容租户上传过带验证的自定义模板),避免叠加重复下拉
for _, col := range []string{"A", "E", "F", "G", "H", "J"} {
_ = f.DeleteDataValidation(sheet, fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1))
}
// 动态选项 → 隐藏辅助列 → 数据验证下拉(取值/落点/prompt 同收集模板 applyList)
applyList := func(optCol, header string, values []string, targetRange string, prompt string) {
if len(values) == 0 {
return
}
if err := f.SetCellValue(sheet, optCol+"1", header); err != nil {
return
}
for i, v := range values {
if err := f.SetCellValue(sheet, fmt.Sprintf("%s%d", optCol, i+2), v); err != nil {
return
}
}
_ = f.SetColVisible(sheet, optCol, false)
dv := excelize.NewDataValidation(true)
dv.SetSqref(targetRange)
dv.Type = "list"
dv.Formula1 = fmt.Sprintf("$%s$2:$%s$%d", optCol, optCol, len(values)+1)
if prompt != "" {
dv.SetInput(header, prompt)
}
_ = f.AddDataValidation(sheet, dv)
}
applyList(courseLibOptColDept, "所属部门(组织架构)", deptNames,
fmt.Sprintf("A2:A%d", courseLibTargetRows+1), "从下拉选择组织架构部门;导入后按部门名自动关联")
applyList(courseLibOptColCat, "课程分类(配置)", categories,
fmt.Sprintf("E2:E%d", courseLibTargetRows+1), "从下拉选择配置中心「课程分类」;分类之外可直接填写,导入后保存为自定义分类")
applyList(courseLibOptColLect, "讲师(员工档案)", empNames,
fmt.Sprintf("H2:H%d", courseLibTargetRows+1), "可从下拉选择系统员工,也可直接填写外部讲师姓名")
// 固定内联列表下拉(非阻断式可自由填写)
inlineList := func(col, values, title, prompt string) {
dv := excelize.NewDataValidation(true)
dv.SetSqref(fmt.Sprintf("%s2:%s%d", col, col, courseLibTargetRows+1))
dv.Type = "list"
dv.Formula1 = values
dv.SetInput(title, prompt)
_ = f.AddDataValidation(sheet, dv)
}
inlineList("F", `"必修课,选修课"`, "类型", "从下拉选择必修课或选修课;留空默认必修课")
inlineList("G", `"线上,线下"`, "线上或线下", "从下拉选择线上或线下;留空默认线下")
inlineList("J", `"已有课件,暂无课件"`, "课件收集", "从下拉选择已有课件或暂无课件;也可直接填写课件名称")
}
// SaveTrainingTemplate stores a tenant custom template (content-type validated upstream).
func (s *trainingService) SaveTrainingTemplate(ctx context.Context, tenantID uint64, key, fileName string, data []byte, updaterID string) (*types.TrainingTemplateMeta, error) {
if !trainingtemplates.IsKnown(key) {
@@ -0,0 +1,64 @@
package service
import (
"bytes"
"testing"
"github.com/stretchr/testify/require"
"github.com/xuri/excelize/v2"
)
// 课程管理模板下拉注入(enrichCourseLibraryTemplate 的纯 xlsx 部分):
// 部门/分类/讲师走隐藏辅助列,类型/线上或线下/课件收集内联列表,共 6 组下拉。
func TestApplyCourseLibraryDropdowns(t *testing.T) {
f := excelize.NewFile()
sheet := "课程管理"
f.SetSheetName("Sheet1", sheet)
// 模拟内置资产表头(与 trainingtemplates.TestCourseLibraryDefaultAsset 同口径)
for i, h := range []string{
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集",
} {
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
require.NoError(t, f.SetCellValue(sheet, cell, h))
}
applyCourseLibraryDropdowns(f, sheet,
[]string{"财务部", "技术部"},
[]string{"专业技能类", "通用技能类"},
[]string{"何莲", "王睿喆", "陆彦彤"})
buf, err := f.WriteToBuffer()
require.NoError(t, err)
f2, err := excelize.OpenReader(bytes.NewReader(buf.Bytes()))
require.NoError(t, err)
defer f2.Close()
// 6 组数据验证全部挂上(部门/分类/讲师/类型/线上或线下/课件收集)
dvs, err := f2.GetDataValidations(sheet)
require.NoError(t, err)
require.GreaterOrEqual(t, len(dvs), 6)
// 隐藏辅助列取值:CA=部门 / CB=分类 / CC=讲师
v, err := f2.GetCellValue(sheet, "CA2")
require.NoError(t, err)
require.Equal(t, "财务部", v)
v, err = f2.GetCellValue(sheet, "CB2")
require.NoError(t, err)
require.Equal(t, "专业技能类", v)
v, err = f2.GetCellValue(sheet, "CC2")
require.NoError(t, err)
require.Equal(t, "何莲", v)
// 重复注入不叠加:清旧验证后再挂,总数保持 6
applyCourseLibraryDropdowns(f2, sheet,
[]string{"财务部"}, []string{"专业技能类"}, []string{"何莲"})
buf2, err := f2.WriteToBuffer()
require.NoError(t, err)
f3, err := excelize.OpenReader(bytes.NewReader(buf2.Bytes()))
require.NoError(t, err)
defer f3.Close()
dvs, err = f3.GetDataValidations(sheet)
require.NoError(t, err)
require.Len(t, dvs, 6)
}