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)
}
@@ -4,27 +4,29 @@
// 未上传或恢复默认时回退到本包内置文件。
// 需求收集默认模板自 2026-11 起为公司标准「教育训练需求表模板.xlsx」
// (原 .xls 版重制为 xlsx 并增加「计划培训时间」列):xlsx 可被 excelize
// 解析,服务层下载时会按新布局注入组织架构部门/员工下拉
// (training_template.go enrichDemandTemplate,部门 B/参加人员 D/讲师 I)。
// 解析,服务层下载时会按新布局注入组织架构部门/员工下拉与表头归一
// (training_template.go enrichDemandTemplate,部门 B/适合人员 D/内/外培训 G/讲师 I)。
package trainingtemplates
import (
"embed"
)
//go:embed demand_collection.xlsx question_bank.xlsx
//go:embed demand_collection.xlsx question_bank.xlsx course_library.xlsx
var files embed.FS
// defaultNames 内置默认文件的业务名(展示给用户,与 docs/moban 原名一致)。
var defaultNames = map[string]string{
"demand_collection": "教育训练需求表模板.xlsx",
"question_bank": "部门培训课程试题(题库导入版)模板.xlsx",
"course_library": "课程管理导入模板.xlsx",
}
// assetNames 内置资产文件名(ASCII,go:embed 友好)。
var assetNames = map[string]string{
"demand_collection": "demand_collection.xlsx",
"question_bank": "question_bank.xlsx",
"course_library": "course_library.xlsx",
}
// IsKnown reports whether key is a managed template key.
@@ -1,13 +1,17 @@
package trainingtemplates
import (
"bytes"
"testing"
"github.com/stretchr/testify/require"
"github.com/xuri/excelize/v2"
)
// 2026-11 需求收集默认模板为公司标准「教育训练需求表模板.xlsx」
// (原 .xls 重制为 xlsx 并增加「计划培训时间」列),防止资产缺失或损坏。
// 表头锁定导入/展示口径(000154):适合人员(D)/内/外培训(G);改动表头须
// 同步 PlanPanel onImportDemandExcel 列名与 enrichDemandTemplate 表头归一。
func TestDemandCollectionDefaultAsset(t *testing.T) {
name, ok := DefaultFileName("demand_collection")
require.True(t, ok)
@@ -19,7 +23,48 @@ func TestDemandCollectionDefaultAsset(t *testing.T) {
// zip 魔数(PK\x03\x04)= xlsx 容器
require.Equal(t, []byte{0x50, 0x4b, 0x03, 0x04}, data[:4])
// 表头行(第 2 行,首行为标题合并单元格)与前端导入解析口径一致
f, err := excelize.OpenReader(bytes.NewReader(data))
require.NoError(t, err)
defer f.Close()
rows, err := f.GetRows("需求表")
require.NoError(t, err)
require.GreaterOrEqual(t, len(rows), 2)
require.Equal(t, []string{
"编号", "部门", "课程名称", "适合人员", "地 点", "培訓費用(RMB)",
"内/外培训", "计划培训时间", "讲师", "备注",
}, rows[1])
require.True(t, IsKnown("demand_collection"))
require.True(t, IsKnown("question_bank"))
require.True(t, IsKnown("course_library"))
require.False(t, IsKnown("other"))
}
// 课程管理默认模板(000151):表头行 = 导入解析口径(所属部门/课程名称/
// 课程说明/适合人员/课程分类/类型(必修课或选修课)/线上或线下/讲师/
// 时长(学时)/课件收集;仅表头无示例行,防止示例被误导入),防止资产缺失或损坏。
// 下载时服务层会动态注入下拉(enrichCourseLibraryTemplate),内置资产只含表头。
func TestCourseLibraryDefaultAsset(t *testing.T) {
name, ok := DefaultFileName("course_library")
require.True(t, ok)
require.Equal(t, "课程管理导入模板.xlsx", name)
data, err := Default("course_library")
require.NoError(t, err)
require.Greater(t, len(data), 1000)
// zip 魔数(PK\x03\x04)= xlsx 容器
require.Equal(t, []byte{0x50, 0x4b, 0x03, 0x04}, data[:4])
// 表头行与导入解析口径一致(改动表头须同步 LibraryPanel onImportExcel 列名)
f, err := excelize.OpenReader(bytes.NewReader(data))
require.NoError(t, err)
defer f.Close()
rows, err := f.GetRows("课程管理")
require.NoError(t, err)
require.NotEmpty(t, rows)
require.Equal(t, []string{
"所属部门", "课程名称", "课程说明", "适合人员", "课程分类",
"类型(必修课或选修课)", "线上或线下", "讲师", "时长(学时)", "课件收集",
}, rows[0])
}
+253 -24
View File
@@ -157,8 +157,9 @@ func (h *Handler) callerDataScope(c *gin.Context) (dataScope, *types.TrainingMem
}
}
// callerDeptScope 计划类列表的部门范围限定:纯课长(有课长角色、无人事/经理
// 全局视角)只能查询本部门数据,返回其所在部门 ID;其余角色返回空串(不限定)。
// callerDeptScope 计划类列表的部门范围限定:人事/空间管理员为全局视角(返回
// 空串不限定);经理/课长(含继承课长的自定义角色)只能查询本部门数据,返回其
// 所在部门 ID;其余角色(讲师/学员)不限定(本就无管理入口)。
func (h *Handler) callerDeptScope(c *gin.Context) string {
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
@@ -169,12 +170,14 @@ func (h *Handler) callerDeptScope(c *gin.Context) string {
return ""
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
if types.HasTrainingRole(roles, types.TrainingRoleHR) ||
types.HasTrainingRole(roles, types.TrainingRoleManager) ||
!types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
// 人事全量;经理继承课长权限组,与课长一致收窄本部门
if types.HasTrainingRole(roles, types.TrainingRoleHR) {
return ""
}
return member.DeptID
if types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
return member.DeptID
}
return ""
}
// checkCourseVisibility 课程详情可见性:全局视角与已发布课程对所有人开放;
@@ -314,7 +317,8 @@ func (h *Handler) ImportMembers(c *gin.Context) {
// 企微 userid(培训提醒推送目标;空串=解绑)。
func (h *Handler) UpdateMemberWecomUserid(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
// 经理与人事同权(000159):职称角色页对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
var req struct {
@@ -341,10 +345,10 @@ func rolesToJSON(roles []string) types.JSON {
return types.JSON(data)
}
// UpdateMemberRoles PUT /training/members/:id/roles
// UpdateMemberRoles PUT /training/members/:id/roles — 经理与人事同权(000159)。
func (h *Handler) UpdateMemberRoles(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
var req struct {
@@ -391,6 +395,17 @@ func (h *Handler) ListDemands(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
}
// ListDemandYears GET /training/demands/years — 需求库实际年份去重列表(降序),
// 年度需求收集页年份下拉数据源(前端默认选中最新一年);纯课长收窄本部门口径。
func (h *Handler) ListDemandYears(c *gin.Context) {
years, err := h.svc.ListDemandYears(c.Request.Context(), callerTenantID(c), h.callerDeptScope(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": years})
}
// saveDemandRequest is the body of POST /training/demands.
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
@@ -485,6 +500,8 @@ func (h *Handler) SaveDemand(c *gin.Context) {
_ = c.Error(err)
return
}
// 需求讲师回写课程管理(000156):在线改选讲师后课程管理同步追加(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), []*types.TrainingDemand{demand})
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
}
@@ -550,6 +567,7 @@ func (h *Handler) ImportDemands(c *gin.Context) {
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName,
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
TargetCount: item.TargetCount, Hours: item.Hours, ExpectMonth: item.ExpectMonth,
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
})
@@ -559,22 +577,57 @@ func (h *Handler) ImportDemands(c *gin.Context) {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result)}})
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands)
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}})
}
// ConfirmDemand POST /training/demands/:id/confirm — 人事复核确认。
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
// 仅「需求归属部门」内、职称角色为经理的成员可确认,其余人员一律提示联系部门经理。
const demandConfirmDenied = "暂无权限,请联系部门经理~"
// ConfirmDemand POST /training/demands/:id/confirm — 经理核验确认(部门+角色双校验)。
// 仅「需求归属部门的成员且职称角色为经理」可核验(000154 收窄:人事/空间管理员/
// 其他部门经理一律拒绝),统一提示「暂无权限,请联系部门经理~」;
// 部门校验先于确认落库,避免越权时已改状态。
func (h *Handler) ConfirmDemand(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
tenantID, userID := callerTenantID(c), callerUserID(c)
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
if err != nil {
_ = c.Error(err)
return
}
demand, err := h.svc.ConfirmDemand(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
if member == nil {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList())
if !types.HasTrainingRole(roles, types.TrainingRoleManager) {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
existing, err := h.svc.GetDemand(ctx, tenantID, c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
// 本部门口径:仅可核验本部门需求(部门缺失的需求先由人事/提报人补全部门)。
if existing.DeptID == "" || existing.DeptID != member.DeptID {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
demand, err := h.svc.ConfirmDemand(ctx, tenantID, c.Param("id"), userID)
if err != nil {
_ = c.Error(err)
return
}
// 已确认需求自动生成草稿课程到课程管理(fail-open,不阻断确认)。
h.syncDemandCourse(ctx, callerTenantID(c), demand, callerUserID(c))
h.syncDemandCourse(ctx, tenantID, demand, userID)
// 确认转月培训计划后自动推送讲师与部门课长维护(000157,站内+企微,fail-open)。
h.notifyDemandConfirmed(ctx, tenantID, userID, demand)
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
}
@@ -601,12 +654,25 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
DeptIDs: sliceToJSON([]string{demand.DeptID}),
PostScope: demand.PostScope,
}
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
course.SourceDemandID = demand.ID
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
for _, item := range libItems {
if item != nil && item.Name == demand.CourseName {
course.LibraryCourseID = item.ID
break
}
}
}
// 授课时间默认取需求「期望月份」(YYYY-MM,课程管理侧可修改并留版本记录)。
if demand.Year > 0 && demand.ExpectMonth >= 1 && demand.ExpectMonth <= 12 {
course.TeachTime = fmt.Sprintf("%04d-%02d", demand.Year, demand.ExpectMonth)
}
// 计划培训时间:需求已填则原样同步到课程(YYYY-MM-DD HH:mm / YYYY-MM-DD)。
course.PlannedTime = trimSpace(demand.PlannedTime)
// 计划培训月份:需求侧为「YYYY-M」(如 2027-1),归一为课程口径 YYYY-MM;
// 旧日期格式(YYYY-MM-DD 等)原样同步。
course.PlannedTime = demandPlannedMonthOf(trimSpace(demand.PlannedTime))
// 需求录入信息全量同步(000150 补充的课程侧落点),课程详情弹窗只读回显。
// 内/外培训、厂区、地点、培训次数、备注原样带入;外部讲师仅在无系统讲师时生效。
externalLecturer := trimSpace(demand.LecturerExternal)
@@ -701,6 +767,164 @@ func splitNames(raw string) []string {
return out
}
// trainingDeptRoleRecipients 取指定部门具有任一目标职称角色(按权限分配展开后)
// 的在职成员 user_id;部门为空或查询失败返回空(fail-open 供推送场景使用)。
func (h *Handler) trainingDeptRoleRecipients(ctx context.Context, tenantID uint64, deptID string, want ...types.TrainingRole) []string {
if deptID == "" {
return nil
}
members, _, err := h.svc.ListMembers(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil {
return nil
}
out := []string{}
for _, m := range members {
if m == nil || m.DeptID != deptID || m.UserID == "" {
continue
}
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, m.TrainingRoleList())
for _, w := range want {
if types.HasTrainingRole(roles, w) {
out = append(out, m.UserID)
break
}
}
}
return out
}
// notifyDemandVerify 需求导入后自动推送(000157):按部门聚合,站内+企微通知
// 该部门经理(职称角色经理)进行核实【确认】;fail-open 不阻断导入。
// 返回成功送达的通知数(写入导入响应,前端提示)。
func (h *Handler) notifyDemandVerify(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand) int {
byDept := map[string][]string{}
year := 0
for _, d := range demands {
if d == nil || d.DeptID == "" || trimSpace(d.CourseName) == "" {
continue
}
byDept[d.DeptID] = append(byDept[d.DeptID], trimSpace(d.CourseName))
if d.Year > 0 && year == 0 {
year = d.Year
}
}
if len(byDept) == 0 {
return 0
}
deptNames := map[string]string{}
if depts, err := h.svc.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
if d != nil {
deptNames[d.ID] = d.Name
}
}
}
sent := 0
for deptID, courses := range byDept {
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, deptID, types.TrainingRoleManager)
if len(recipients) == 0 {
continue
}
name := deptNames[deptID]
if name == "" {
name = deptID
}
title := fmt.Sprintf("【年度培训需求核验】%d年度 %s 培训需求待核验", year, name)
content := fmt.Sprintf(
"%s 新导入 %d 条年度培训需求(课程:%s)。请登录 AIDO → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。",
name, len(courses), strings.Join(courses, "、"),
)
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year))
if err != nil {
logger.Error(ctx, "Failed to notify dept managers for demand verify", err)
continue
}
sent += n
}
return sent
}
// notifyDemandConfirmed 需求确认转月培训计划后自动推送(000157):站内+企微通知
// 该课程讲师与部门课长维护培训相关信息(讲师维护课程信息,课长安排授课计划);
// 确认操作人自身不重复通知;fail-open 不阻断确认。
func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, operatorID string, demand *types.TrainingDemand) {
if demand == nil {
return
}
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, demand.DeptID, types.TrainingRoleSupervisor)
recipients = append(recipients, trimSpace(demand.LecturerID))
seen := map[string]bool{}
final := []string{}
for _, uid := range recipients {
if uid == "" || uid == operatorID || seen[uid] {
continue
}
seen[uid] = true
final = append(final, uid)
}
if len(final) == 0 {
return
}
title := fmt.Sprintf("【培训计划维护】%s 已确认转入月培训计划", demand.CourseName)
content := fmt.Sprintf(
"%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:AIDO → 企业培训 → 月培训计划。",
demand.Year, demand.CourseName,
)
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID); err != nil {
logger.Error(ctx, "Failed to notify lecturer and supervisors after demand confirm", err)
}
}
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
byName := map[string]*types.TrainingDemand{}
for _, d := range demands {
if d == nil || trimSpace(d.CourseName) == "" {
continue
}
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" {
continue
}
if _, ok := byName[d.CourseName]; !ok {
byName[d.CourseName] = d
}
}
if len(byName) == 0 {
return
}
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil {
logger.Error(ctx, "Failed to list course library for lecturer sync", err)
return
}
for _, item := range items {
if item == nil {
continue
}
d, ok := byName[item.Name]
if !ok {
continue
}
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
continue
}
updated := *item
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync demand lecturer to course library", err)
continue
}
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
if err := h.svc.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role on demand sync", err)
}
}
}
// GenerateAnnualPlan POST /training/annual-plans/generate — AI 汇总生成年度排期。
func (h *Handler) GenerateAnnualPlan(c *gin.Context) {
ctx := c.Request.Context()
@@ -923,6 +1147,8 @@ type saveCourseRequest struct {
SessionCount int `json:"session_count"`
LecturerExternal string `json:"lecturer_external"`
Remark string `json:"remark"`
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」选择课程后关联)。
LibraryCourseID string `json:"library_course_id"`
}
// SaveCourse POST /training/courses — 课程创建(线下/线上双向导数据源)。
@@ -946,6 +1172,7 @@ func (h *Handler) SaveCourse(c *gin.Context) {
PlannedTime: req.PlannedTime,
TrainType: req.TrainType, Plant: req.Plant, Location: req.Location,
SessionCount: req.SessionCount, LecturerExternal: req.LecturerExternal, Remark: req.Remark,
LibraryCourseID: req.LibraryCourseID,
}, callerUserID(c))
if err != nil {
_ = c.Error(err)
@@ -1027,15 +1254,16 @@ func (h *Handler) ImportQuestionBankFromKnowledge(c *gin.Context) {
return
}
var req struct {
KnowledgeID string `json:"knowledge_id" binding:"required"`
Name string `json:"name"`
CourseID string `json:"course_id"`
KnowledgeID string `json:"knowledge_id" binding:"required"`
Name string `json:"name"`
CourseID string `json:"course_id"`
LibraryCourseID string `json:"library_course_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
bank, err := h.svc.ImportQuestionBankFromKnowledge(ctx, callerTenantID(c), req.KnowledgeID, req.Name, req.CourseID, callerUserID(c))
bank, err := h.svc.ImportQuestionBankFromKnowledge(ctx, callerTenantID(c), req.KnowledgeID, req.Name, req.CourseID, req.LibraryCourseID, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
@@ -1112,15 +1340,16 @@ func (h *Handler) ImportGeneratedQuestionBank(c *gin.Context) {
return
}
var req struct {
CourseID string `json:"course_id"`
Name string `json:"name"`
Questions []*types.TrainingQuestion `json:"questions" binding:"required"`
CourseID string `json:"course_id"`
LibraryCourseID string `json:"library_course_id"`
Name string `json:"name"`
Questions []*types.TrainingQuestion `json:"questions" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
bank, err := h.svc.ImportGeneratedQuestionBank(ctx, callerTenantID(c), req.CourseID, req.Name, req.Questions, callerUserID(c))
bank, err := h.svc.ImportGeneratedQuestionBank(ctx, callerTenantID(c), req.CourseID, req.LibraryCourseID, req.Name, req.Questions, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
@@ -0,0 +1,236 @@
package training
import (
"fmt"
"net/http"
"academy/internal/errors"
"academy/internal/filetransport"
"academy/internal/types"
"academy/internal/utils"
"github.com/gin-gonic/gin"
)
// ---------------------------------------------------------------------------
// 课程管理(课程资产主数据,tr_course_library,000151)。
// 字段:课程名称/所属部门(org_depts)/说明/适合人员/分类(配置中心
// course_category_dict 可配,可自定义)/类型(必修课/选修课)/线上或线下/
// 讲师/时长/课件。月培训计划的「计划名称」从本表选择。
// 列表 Viewer 可读(月培训计划下拉同源);维护动作限人事/课长/讲师。
// ---------------------------------------------------------------------------
// saveCourseLibraryRequest is the body of POST /training/course-library.
type saveCourseLibraryRequest struct {
ID string `json:"id"`
Name string `json:"name" binding:"required"`
OwnerDeptID string `json:"owner_dept_id"`
Description string `json:"description"`
SuitableMembers string `json:"suitable_members"`
Category string `json:"category"`
Type string `json:"type"`
Mode string `json:"mode"`
LecturerID string `json:"lecturer_id"`
LecturerExternal string `json:"lecturer_external"`
Hours float64 `json:"hours"`
MaterialName string `json:"material_name"`
// ClearFile 移除课件文件(前端「移除」按钮;置 true 强制清空 file_* 三列)。
ClearFile bool `json:"clear_file"`
}
// toCourseLibrary maps the request body onto the domain model.
func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary {
return &types.TrainingCourseLibrary{
ID: req.ID,
Name: req.Name,
OwnerDeptID: req.OwnerDeptID,
Description: req.Description,
SuitableMembers: req.SuitableMembers,
Category: req.Category,
Type: req.Type,
Mode: req.Mode,
LecturerID: req.LecturerID,
LecturerExternal: req.LecturerExternal,
Hours: req.Hours,
MaterialName: req.MaterialName,
ClearFile: req.ClearFile,
}
}
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
func (h *Handler) ListCourseLibrary(c *gin.Context) {
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), listQueryFromRequest(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
}
// SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。
func (h *Handler) SaveCourseLibraryItem(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req saveCourseLibraryRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
item, err := h.svc.SaveCourseLibraryItem(c.Request.Context(), callerTenantID(c), toCourseLibrary(req), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
// DeleteCourseLibraryItem DELETE /training/course-library/:id — 删除(人事/课长)。
func (h *Handler) DeleteCourseLibraryItem(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
if err := h.svc.DeleteCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// SetCourseLibraryPublishStatus POST /training/course-library/:id/:action
// — 课程条目发布/下线(000154;action=publish|offline,人事/课长/讲师)。
// 发布后课程进入培训中心「和信课程」目录;下线即从目录撤回。
func (h *Handler) SetCourseLibraryPublishStatus(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
status := ""
switch c.Param("action") {
case "publish":
status = "published"
case "offline":
status = "offline"
default:
_ = c.Error(errors.NewBadRequestError("不支持的操作(仅 publish/offline)"))
return
}
if err := h.svc.SetCourseLibraryPublishStatus(c.Request.Context(), callerTenantID(c), c.Param("id"), status); err != nil {
_ = c.Error(err)
return
}
item, err := h.svc.GetCourseLibraryItem(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
// ImportCourseLibraryRequest is the body of POST /training/course-library/import
// (前端解析 Excel 后逐行提交,与需求导入同口径)。
type ImportCourseLibraryRequest struct {
Items []saveCourseLibraryRequest `json:"items" binding:"required,min=1"`
}
// ImportCourseLibrary POST /training/course-library/import — 批量导入。
func (h *Handler) ImportCourseLibrary(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req ImportCourseLibraryRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
items := make([]*types.TrainingCourseLibrary, 0, len(req.Items))
for _, row := range req.Items {
items = append(items, toCourseLibrary(row))
}
imported, err := h.svc.ImportCourseLibraryItems(c.Request.Context(), callerTenantID(c), items, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": imported}})
}
// ExportCourseLibraryRequest is the body of POST /training/course-library/export
// (ids 空 = 全量导出;当前筛选由前端传当前列表 id)。
type ExportCourseLibraryRequest struct {
IDs []string `json:"ids"`
}
// ExportCourseLibrary POST /training/course-library/export — 课程管理 xlsx 下载。
func (h *Handler) ExportCourseLibrary(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req ExportCourseLibraryRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
filename, data, err := h.svc.ExportCourseLibrary(c.Request.Context(), callerTenantID(c), req.IDs)
if err != nil {
_ = c.Error(err)
return
}
c.Header("Content-Disposition", "attachment; filename="+filename)
c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data)
}
// UploadCourseLibraryMaterial POST /training/course-library/:id/material —
// 上传课件原始文件(multipart: file)。
func (h *Handler) UploadCourseLibraryMaterial(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
fh, err := c.FormFile("file")
if err != nil {
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
return
}
if fh.Size > utils.GetMaxFileSizeMB()*1024*1024 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", utils.GetMaxFileSizeMB())))
return
}
item, err := h.svc.UploadCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), fh, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
// AttachCourseLibraryMaterialFromKb POST /training/course-library/:id/material/from-kb
// — 从知识库「企业培训(课件)」选择已有文档作为课程课件(body: knowledge_id)。
func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req struct {
KnowledgeID string `json:"knowledge_id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
item, err := h.svc.AttachCourseLibraryMaterialFromKnowledge(c.Request.Context(), callerTenantID(c), c.Param("id"), req.KnowledgeID, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
// 课件原始文件流(下载/在线预览)。
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if err := filetransport.Serve(c.Writer, c.Request, rc, filetransport.Options{Filename: fileName}); err != nil {
_ = c.Error(err)
}
}
+26 -6
View File
@@ -2,6 +2,7 @@ package training
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
@@ -36,6 +37,20 @@ func parseFlexibleTime(raw string) *time.Time {
return nil
}
// demandPlannedMonthOf 需求侧「计划培训月份」(YYYY-M,如 2027-1)归一为课程口径
// YYYY-MM(2027-01);其余格式(旧 YYYY-MM-DD 日期等)原样返回。
func demandPlannedMonthOf(raw string) string {
parts := strings.SplitN(raw, "-", 2)
if len(parts) == 2 {
y, yErr := strconv.Atoi(strings.TrimSpace(parts[0]))
m, mErr := strconv.Atoi(strings.TrimSpace(parts[1]))
if yErr == nil && mErr == nil && y >= 1000 && y <= 9999 && m >= 1 && m <= 12 {
return fmt.Sprintf("%04d-%02d", y, m)
}
}
return raw
}
// sliceToJSON encodes a string slice into jsonb payload.
func sliceToJSON(items []string) types.JSON {
if len(items) == 0 {
@@ -79,7 +94,7 @@ func (h *Handler) ImportQuestionBankExcel(c *gin.Context) {
}
bank, err := h.svc.ImportQuestionBankExcel(
ctx, callerTenantID(c),
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), c.PostForm("course_id"),
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), c.PostForm("course_id"), c.PostForm("library_course_id"),
file, callerUserID(c),
)
if err != nil {
@@ -209,9 +224,10 @@ func (h *Handler) SettleLecturerScores(c *gin.Context) {
}
// SeedRuleConfigs POST /training/rule-configs/seed — 初始化默认规则(已存在不覆盖)。
// 经理与人事同权(000158):配置中心对经理开放。
func (h *Handler) SeedRuleConfigs(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
seeded, err := h.svc.SeedRuleConfigs(ctx, callerTenantID(c), callerUserID(c))
@@ -517,7 +533,8 @@ func (h *Handler) ListRuleConfigs(c *gin.Context) {
// SaveRuleConfig PUT /training/rule-configs/:key — 业务规则配置(人事确认后修改)。
func (h *Handler) SaveRuleConfig(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
// 经理与人事同权(000158):配置中心对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
var req struct {
@@ -617,7 +634,8 @@ func (h *Handler) PushTestNotification(c *gin.Context) {
// summary 带回给前端展示)。
func (h *Handler) SyncWecomUseridsFromOA(c *gin.Context, apply bool) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
// 经理与人事同权(000159):职称角色页对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
summary, err := h.svc.SyncWecomUseridsFromOA(ctx, callerTenantID(c), apply)
@@ -693,7 +711,8 @@ func (h *Handler) DownloadTrainingTemplate(c *gin.Context) {
// UploadTrainingTemplate POST /training/templates/:key/upload — 上传自定义模板
// (人事;校验扩展名与大小,入库后各下载入口即刻生效)。
func (h *Handler) UploadTrainingTemplate(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR) {
// 经理与人事同权(000158):配置中心对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
file, err := c.FormFile("file")
@@ -729,7 +748,8 @@ func (h *Handler) UploadTrainingTemplate(c *gin.Context) {
// ResetTrainingTemplate DELETE /training/templates/:key — 恢复内置默认模板
// (人事;删除租户自定义版本,下载回退内置文件)。
func (h *Handler) ResetTrainingTemplate(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR) {
// 经理与人事同权(000158):配置中心对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
if err := h.svc.ResetTrainingTemplate(c.Request.Context(), callerTenantID(c), c.Param("key"), callerUserID(c)); err != nil {
@@ -0,0 +1,167 @@
package training
import (
"net/http"
"academy/internal/errors"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// ---------------------------------------------------------------------------
// 课程管理 · 试题维护(000153)
// 试题随课程管理课程维护:课程条目下题库列表/Excel 导入/AI 出题,以及
// 题库删除与单题级增删改查;月度计划选课后经 library_course_id 回退取卷。
// 权限口径与课程管理一致:维护动作限人事/课长/讲师。
// ---------------------------------------------------------------------------
// ListLibraryCourseQuestionBanks GET /training/course-library/:id/question-banks
// — 课程条目下的题库列表(试题维护抽屉)。
func (h *Handler) ListLibraryCourseQuestionBanks(c *gin.Context) {
banks, err := h.svc.ListLibraryCourseQuestionBanks(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": banks})
}
// ImportLibraryCourseQuestionBank POST /training/course-library/:id/question-banks/import
// — Excel 批量导入题库并挂课程管理条目(multipart: file[name][dept_id])。
// 同名重导入即替换;原始 Excel 自动同步「企业培训(题库)」知识库(服务层 fail-open)。
func (h *Handler) ImportLibraryCourseQuestionBank(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
file, err := c.FormFile("file")
if err != nil {
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
return
}
bank, err := h.svc.ImportQuestionBankExcel(
ctx, callerTenantID(c),
trimSpace(c.PostForm("name")), c.PostForm("dept_id"), "", c.Param("id"),
file, callerUserID(c),
)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": bank})
}
// LinkQuestionBankToLibraryCourse PUT /training/course-library/:id/question-banks/link
// — 更换课程条目的试题(000156):所选题库整体替换该条目当前挂接的题库,
// 更换后自动同步到课程管理对应课程(月计划详情「试题 · 更换」入口)。
func (h *Handler) LinkQuestionBankToLibraryCourse(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req struct {
BankID string `json:"bank_id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.svc.LinkQuestionBankToLibraryCourse(ctx, callerTenantID(c), c.Param("id"), req.BankID); err != nil {
_ = c.Error(err)
return
}
banks, err := h.svc.ListLibraryCourseQuestionBanks(ctx, callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": banks})
}
// GenerateLibraryCourseQuestions POST /training/course-library/:id/generate-questions
// — 课程管理课件 AI 出题(课件已同步知识库;预览编辑用,不落库)。
func (h *Handler) GenerateLibraryCourseQuestions(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req struct {
Count int `json:"count"`
}
_ = c.ShouldBindJSON(&req)
questions, err := h.svc.GenerateLibraryCourseQuestions(ctx, callerTenantID(c), callerUserID(c), c.Param("id"), req.Count)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": questions})
}
// DeleteQuestionBank DELETE /training/question-banks/:id — 删除题库
// (连带题目与缓存试卷;试题维护抽屉删除入口)。
func (h *Handler) DeleteQuestionBank(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
if err := h.svc.DeleteQuestionBank(c.Request.Context(), callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// saveQuestionRequest is the body of POST /training/question-banks/:id/questions
// (id 空 = 新增,否则编辑;题干/选项/答案等全字段)。
type saveQuestionRequest struct {
ID string `json:"id"`
Type string `json:"type"`
Stem string `json:"stem" binding:"required"`
Options []string `json:"options"`
Answer string `json:"answer" binding:"required"`
Score float64 `json:"score"`
Difficulty int `json:"difficulty"`
KnowledgePoint string `json:"knowledge_point"`
Analysis string `json:"analysis"`
}
// SaveQuestion POST /training/question-banks/:id/questions — 单题新增/编辑
// (题库 question_count 同步刷新)。
func (h *Handler) SaveQuestion(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req saveQuestionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
q, err := h.svc.SaveQuestion(c.Request.Context(), callerTenantID(c), &types.TrainingQuestion{
ID: req.ID,
BankID: c.Param("id"),
Type: req.Type,
Stem: req.Stem,
Options: sliceToJSON(req.Options),
Answer: req.Answer,
Score: req.Score,
Difficulty: req.Difficulty,
KnowledgePoint: req.KnowledgePoint,
Analysis: req.Analysis,
})
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": q})
}
// DeleteQuestion DELETE /training/question-banks/:id/questions/:qid — 删除单题。
func (h *Handler) DeleteQuestion(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
if err := h.svc.DeleteQuestion(c.Request.Context(), callerTenantID(c), c.Param("qid")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+28
View File
@@ -37,6 +37,8 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// ---- 计划域:年度需求 → 年度排期 → 月度排期 ----
trainingGroup.GET("/demands", h.ListDemands)
// demands/years 需求库实际年份去重列表(年度筛选下拉数据源;静态段先于参数路由注册)。
trainingGroup.GET("/demands/years", h.ListDemandYears)
trainingGroup.POST("/demands", h.SaveDemand)
trainingGroup.POST("/demands/import", g.Contributor(), h.ImportDemands)
trainingGroup.POST("/demands/:id/confirm", g.Contributor(), h.ConfirmDemand)
@@ -75,6 +77,32 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
trainingGroup.DELETE("/courses/:id", g.Contributor(), h.DeleteCourse)
// courses/:id/exam-paper 线上自学考试取卷(确保卷存在,学员视角脱敏)。
trainingGroup.POST("/courses/:id/exam-paper", h.CourseExamPaper)
// ---- 课程管理(课程资产主数据,000151;月培训计划「计划名称」数据源) ----
trainingGroup.GET("/course-library", h.ListCourseLibrary)
trainingGroup.POST("/course-library", g.Contributor(), h.SaveCourseLibraryItem)
trainingGroup.DELETE("/course-library/:id", g.Contributor(), h.DeleteCourseLibraryItem)
// 发布/下线(000154):静态段 :action 须先于 :id 参数段注册区分
trainingGroup.POST("/course-library/:id/publish", g.Contributor(), h.SetCourseLibraryPublishStatus)
trainingGroup.POST("/course-library/:id/offline", g.Contributor(), h.SetCourseLibraryPublishStatus)
// 导入/导出:与需求域同口径(前端解析 Excel 后按行提交;导出 xlsx 下载)。
trainingGroup.POST("/course-library/import", g.Contributor(), h.ImportCourseLibrary)
trainingGroup.POST("/course-library/export", g.Contributor(), h.ExportCourseLibrary)
// 课件原始文件(fileSvc 直存;文档类同步知识库「企业培训(课件)」,000153)。
trainingGroup.POST("/course-library/:id/material", g.Contributor(), h.UploadCourseLibraryMaterial)
// material/from-kb 从知识库「企业培训(课件)」选择已有文档作为课件。
trainingGroup.POST("/course-library/:id/material/from-kb", g.Contributor(), h.AttachCourseLibraryMaterialFromKb)
trainingGroup.GET("/course-library/:id/material/file", h.CourseLibraryMaterialFile)
// ---- 课程管理 · 试题维护(000153):题库/单题随课程条目增删改查 ----
trainingGroup.GET("/course-library/:id/question-banks", h.ListLibraryCourseQuestionBanks)
// question-banks/link 更换课程条目试题(所选题库整体替换,000156;PUT 动态段与静态段共存)
trainingGroup.PUT("/course-library/:id/question-banks/link", g.Contributor(), h.LinkQuestionBankToLibraryCourse)
trainingGroup.POST("/course-library/:id/question-banks/import", g.Contributor(), h.ImportLibraryCourseQuestionBank)
trainingGroup.POST("/course-library/:id/generate-questions", g.Contributor(), h.GenerateLibraryCourseQuestions)
trainingGroup.DELETE("/question-banks/:id", g.Contributor(), h.DeleteQuestionBank)
trainingGroup.POST("/question-banks/:id/questions", g.Contributor(), h.SaveQuestion)
trainingGroup.DELETE("/question-banks/:id/questions/:qid", g.Contributor(), h.DeleteQuestion)
trainingGroup.GET("/sessions", h.ListSessions)
trainingGroup.POST("/sessions", g.Contributor(), h.SaveSession)
trainingGroup.GET("/sessions/:id/enrollments", h.ListEnrollments)
+76 -8
View File
@@ -46,6 +46,8 @@ type TrainingRepository interface {
// ---- 需求域 ----
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
// ListDemandYears 需求库实际年份去重列表(降序,年份下拉数据源;deptID 非空时收窄该部门)。
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
CreateDemand(ctx context.Context, demand *types.TrainingDemand) error
BatchCreateDemands(ctx context.Context, demands []*types.TrainingDemand) error
@@ -75,6 +77,16 @@ type TrainingRepository interface {
CreateCourseChangeLog(ctx context.Context, log *types.TrainingCourseChangeLog) error
ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error)
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
UpdateCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
BatchCreateCourseLibrary(ctx context.Context, items []*types.TrainingCourseLibrary) error
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
CreateSession(ctx context.Context, session *types.TrainingCourseSession) error
@@ -115,24 +127,42 @@ type TrainingRepository interface {
// UnfinishedMembers 返回某月未完成课程签到的成员(滚动/催办用)。
UnfinishedEnrollments(ctx context.Context, tenantID uint64, year, month int) ([]*types.TrainingEnrollment, error)
// ---- 唯一编号(000153) ----
// NextCodeValue 培训业务编号计数器原子递增(UPSERT ... RETURNING),
// key 形如 AP:2026 / MP:202611 / CRS / QB,返回递增后的流水值。
NextCodeValue(ctx context.Context, tenantID uint64, key string) (int64, error)
// ---- 考试域 ----
CreateQuestionBank(ctx context.Context, bank *types.TrainingQuestionBank) error
// ReplaceQuestionBankByName 同名题库重导入即替换(软删旧库及其题目/试卷,
// 返回旧库课程关联供新库继承)。
ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, error)
// 返回旧库的课程/课程管理关联供新库继承)。
ReplaceQuestionBankByName(ctx context.Context, tenantID uint64, name string) (string, string, error)
ListQuestionBanks(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingQuestionBank, int64, error)
GetQuestionBank(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestionBank, error)
// GetQuestionBankByCourse 取课程绑定的题库(线上自学考试入口)。
GetQuestionBankByCourse(ctx context.Context, tenantID uint64, courseID string) (*types.TrainingQuestionBank, error)
// GetQuestionBankByLibraryCourse 取课程管理条目下的题库列表(试题随课程管理维护,000153)。
GetQuestionBankByLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error)
// DeleteQuestionBank 软删题库及其全部题目与缓存试卷。
DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error
// GetSelfStudyPaperByBank 取题库的线上自学卷(session 为空、version=ONLINE)。
GetSelfStudyPaperByBank(ctx context.Context, tenantID uint64, bankID string) (*types.TrainingPaper, error)
UpdateQuestionBankCount(ctx context.Context, tenantID uint64, bankID string, count int) error
// UpdateQuestionBankCourse 反向关联:建课时选择题库,把 bank.course_id 指向课程。
UpdateQuestionBankCourse(ctx context.Context, tenantID uint64, bankID, courseID string) error
// RelinkQuestionBankToLibraryCourse 更换课程管理条目的试题(先解挂旧库再挂新库,000156)。
RelinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error
BatchCreateQuestions(ctx context.Context, questions []*types.TrainingQuestion) error
ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error)
ListQuestionsByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.TrainingQuestion, error)
// 单题级维护(000153,课程管理试题抽屉)。
CreateQuestion(ctx context.Context, question *types.TrainingQuestion) error
GetQuestion(ctx context.Context, tenantID uint64, id string) (*types.TrainingQuestion, error)
UpdateQuestion(ctx context.Context, question *types.TrainingQuestion) error
DeleteQuestion(ctx context.Context, tenantID uint64, id string) error
// CountBankQuestions 统计题库现存未删题目数(增删题目后刷新冗余计数)。
CountBankQuestions(ctx context.Context, tenantID uint64, bankID string) (int64, error)
CreatePaper(ctx context.Context, paper *types.TrainingPaper) error
GetPaper(ctx context.Context, tenantID uint64, id string) (*types.TrainingPaper, error)
@@ -232,6 +262,8 @@ type TrainingService interface {
// 计划域
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
// ListDemandYears 需求库实际年份去重列表(降序,年份下拉数据源;deptID 非空时收窄该部门)。
ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error)
GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error)
SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error)
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error)
@@ -261,6 +293,28 @@ type TrainingService interface {
// ListCourseChangeLogs 课程信息修改版本记录(每次保存一条,变更明细可回溯)。
ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error)
// ---- 课程管理(课程资产主数据) ----
// ListCourseLibraryItems 列表(月培训计划「计划名称」下拉数据源,Viewer 可读)。
ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
// SaveCourseLibraryItem 新增/编辑(id 空 = 新增)。
SaveCourseLibraryItem(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, updaterID string) (*types.TrainingCourseLibrary, error)
// SetCourseLibraryPublishStatus 课程条目发布/下线(000154)。
SetCourseLibraryPublishStatus(ctx context.Context, tenantID uint64, id, status string) error
// GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
DeleteCourseLibraryItem(ctx context.Context, tenantID uint64, id string) error
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后按行提交)。
ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error)
// ExportCourseLibrary 导出 Excel(excelize;ids 空 = 全量)。
ExportCourseLibrary(ctx context.Context, tenantID uint64, ids []string) (filename string, data []byte, err error)
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key)。
UploadCourseLibraryMaterial(ctx context.Context, tenantID uint64, id string, fh *multipart.FileHeader, updaterID string) (*types.TrainingCourseLibrary, error)
// GetCourseLibraryMaterialFile 流式取回课件原始文件。
GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id string) (io.ReadCloser, string, error)
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
// 已有文档作为课程课件(与上传同步同口径)。
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
ListSessions(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseSession, error)
GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error)
ListEnrollmentsForSession(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
@@ -303,15 +357,29 @@ type TrainingService interface {
ImportQuestionBank(ctx context.Context, tenantID uint64, bank *types.TrainingQuestionBank, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
ListQuestions(ctx context.Context, tenantID uint64, bankID string) ([]*types.TrainingQuestion, error)
// ImportQuestionBankExcel 解析 Excel 建题库,并把原始 Excel 同步进系统默认
// 「企业培训(题库)」知识库(同步失败不阻断导入)。
ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error)
// 知识库「企业培训(题库)」;libraryCourseID 非空时题库挂课程管理条目(000153)。
ImportQuestionBankExcel(ctx context.Context, tenantID uint64, name, deptID, courseID, libraryCourseID string, fh *multipart.FileHeader, updaterID string) (*types.TrainingQuestionBank, error)
// ImportQuestionBankFromKnowledge 从「企业培训(题库)」知识库文档解析建题库
// (文档已在知识库,直接挂接 knowledge_id;未指定课程时继承同名旧库关联)。
ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, updaterID string) (*types.TrainingQuestionBank, error)
// (同名替换,继承课程关联;libraryCourseID 非空时挂课程管理条目)。
ImportQuestionBankFromKnowledge(ctx context.Context, tenantID uint64, knowledgeID, name, courseID, libraryCourseID, updaterID string) (*types.TrainingQuestionBank, error)
// ListLibraryCourseQuestionBanks 课程管理条目下的题库列表(试题维护抽屉,000153)。
ListLibraryCourseQuestionBanks(ctx context.Context, tenantID uint64, libraryCourseID string) ([]*types.TrainingQuestionBank, error)
// LinkQuestionBankToLibraryCourse 更换课程管理条目的试题(所选题库整体替换,000156)。
LinkQuestionBankToLibraryCourse(ctx context.Context, tenantID uint64, libraryCourseID, bankID string) error
// DeleteQuestionBank 删除题库(连带题目与缓存试卷)。
DeleteQuestionBank(ctx context.Context, tenantID uint64, bankID string) error
// SaveQuestion 单题新增/编辑(题库 question_count 同步刷新,000153)。
SaveQuestion(ctx context.Context, tenantID uint64, q *types.TrainingQuestion) (*types.TrainingQuestion, error)
// DeleteQuestion 删除单题(题库 question_count 同步刷新)。
DeleteQuestion(ctx context.Context, tenantID uint64, questionID string) error
// GenerateCourseQuestions AI 课件生成试题:取课件知识库分块文本交默认模型出题(不落库)。
GenerateCourseQuestions(ctx context.Context, tenantID uint64, userID, courseID, materialID string, count int) ([]*types.TrainingQuestion, error)
// ImportGeneratedQuestionBank 使用生成/编辑后的题目建题库(关联课程,文本同步知识库)。
ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
// GenerateLibraryCourseQuestions 课程管理课件 AI 出题(读课程管理条目课件的知识库
// 分块,出题不落库,预览确认后经 ImportGeneratedQuestionBank 建库,000153)。
GenerateLibraryCourseQuestions(ctx context.Context, tenantID uint64, userID, libraryCourseID string, count int) ([]*types.TrainingQuestion, error)
// ImportGeneratedQuestionBank 使用生成/编辑后的题目建题库(关联课程,文本同步知识库;
// libraryCourseID 非空时挂课程管理条目)。
ImportGeneratedQuestionBank(ctx context.Context, tenantID uint64, courseID, libraryCourseID, name string, questions []*types.TrainingQuestion, updaterID string) (*types.TrainingQuestionBank, error)
GeneratePaper(ctx context.Context, tenantID uint64, bankID, sessionID string, count int, version, operatorID string) (*types.TrainingPaper, error)
// GetCourseExamPaper 线上自学考试:确保课程线上卷存在并返回学员视角题目。
GetCourseExamPaper(ctx context.Context, tenantID uint64, userID, courseID string) (*types.TrainingPaper, []*types.TrainingQuestion, error)
+98 -12
View File
@@ -362,7 +362,9 @@ type TrainingDemand struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Year int `json:"year" gorm:"not null;index"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
// Code 年计划编号(AP-<year>-####,创建时由服务端生成,000153)。
Code string `json:"code" gorm:"type:varchar(32);default:''"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
SubmitterID string `json:"submitter_id" gorm:"type:varchar(36);default:''"`
CourseName string `json:"course_name" gorm:"type:varchar(255);not null"`
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
@@ -535,6 +537,12 @@ type TrainingCourse struct {
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
// Remark 备注(需求确认同步)。
Remark string `json:"remark" gorm:"type:text;default:''"`
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」从课程管理选择后落此关联;可空)。
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
// PlanCode 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成,000153)。
PlanCode string `json:"plan_code" gorm:"type:varchar(32);default:''"`
// SourceDemandID 来源需求 id(经理确认自动转月度计划时回填,溯源用,000153)。
SourceDemandID string `json:"source_demand_id" gorm:"type:varchar(36);default:''"`
// LecturerName 讲师姓名(联查 users 只读,不落库;覆盖不在讲师名册的需求同步讲师)。
LecturerName string `json:"lecturer_name" gorm:"->"`
}
@@ -557,6 +565,63 @@ type TrainingCourseChangeLog struct {
// TableName pins the physical table name.
func (TrainingCourseChangeLog) TableName() string { return "tr_course_change_logs" }
// TrainingCourseLibrary 课程管理条目(课程资产主数据,000151)。
// 月培训计划的「计划名称」从本表选择,选中计划创建时带 library_course_id 关联。
type TrainingCourseLibrary struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// TenantID 租户隔离。
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
// Name 课程名称(必填)。
Name string `json:"name" gorm:"type:varchar(255);not null"`
// Code 课程编号(CRS-####,创建/导入时由服务端生成,000153)。
Code string `json:"code" gorm:"type:varchar(32);default:''"`
// OwnerDeptID 所属部门(org_depts id;对应需求表「主办单位」,弹窗经组织架构
// 部门下拉选择,批量导入按部门名匹配,未匹配留空)。
OwnerDeptID string `json:"owner_dept_id" gorm:"type:varchar(36);default:''"`
// Description 说明。
Description string `json:"description" gorm:"type:text;default:''"`
// SuitableMembers 适合人员(对应需求表「参加人员」,自由文本,如:财会人员)。
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(255);default:''"`
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
Category string `json:"category" gorm:"type:varchar(64);default:''"`
// Type 类型(required 必修课/elective 选修课)。
Type string `json:"type" gorm:"type:varchar(16);default:'required'"`
// Mode 形式(offline 线下/online 线上)。
Mode string `json:"mode" gorm:"type:varchar(16);default:'offline'"`
// LecturerID 讲师(员工 user id;与外部讲师姓名二选一)。
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
// LecturerExternal 外部讲师姓名(导入未匹配到员工名册时落此)。
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
// Hours 时长(学时)。
Hours float64 `json:"hours" gorm:"default:0"`
// MaterialName 课件名称登记(多个用、分隔;与文件二选一或并存)。
MaterialName string `json:"material_name" gorm:"type:varchar(255);default:''"`
// FileKey/FileName 课件原始文件(fileSvc 存取,可空;经专端点上传/下载)。
FileKey string `json:"file_key" gorm:"type:varchar(512);default:''"`
FileName string `json:"file_name" gorm:"type:varchar(255);default:''"`
// FileSize 课件文件字节数。
FileSize int64 `json:"file_size" gorm:"default:0"`
// KnowledgeID 课件同步知识库「企业培训(课件)」后的文档 id(视频类留空,000153,AI 出题依赖)。
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
// PublishStatus 发布状态(000154):draft 草稿/published 已发布/offline 已下线;
// 培训中心「和信课程」目录仅展示已发布且部门范围覆盖查看人的课程。
PublishStatus string `json:"publish_status" gorm:"type:varchar(16);default:'draft'"`
// ClearFile 课件文件移除标记(请求侧瞬态,不落库:置 true 时强制清空 file_* 三列)。
ClearFile bool `json:"clear_file" gorm:"-"`
// CreatorID 创建人(平台用户 id)。
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
// LecturerName 讲师姓名(联查 users 只读,不落库)。
LecturerName string `json:"lecturer_name" gorm:"->"`
// OwnerDeptName 所属部门名(联查 org_depts 只读,不落库)。
OwnerDeptName string `json:"owner_dept_name" gorm:"->"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
}
// TableName pins the physical table name.
func (TrainingCourseLibrary) TableName() string { return "tr_course_library" }
// TrainingCourseStudyStats 课程维度的学习/考试参与成员聚合(课程管理列表状态列输入)。
type TrainingCourseStudyStats struct {
// SignedMembers 已签到成员(线下参与)。
@@ -731,17 +796,21 @@ const (
// TrainingQuestionBank 题库。
type TrainingQuestionBank struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Name string `json:"name" gorm:"type:varchar(255);not null"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
CourseID string `json:"course_id" gorm:"type:varchar(36);default:''"`
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
QuestionCount int `json:"question_count" gorm:"default:0"`
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
// Code 试题库编号(QB-####,导入/创建时由服务端生成,000153)。
Code string `json:"code" gorm:"type:varchar(32);default:''"`
Name string `json:"name" gorm:"type:varchar(255);not null"`
// LibraryCourseID 课程管理条目 id(试题随课程管理维护,可与 course_id 并存,000153)。
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
DeptID string `json:"dept_id" gorm:"type:varchar(36);default:''"`
CourseID string `json:"course_id" gorm:"type:varchar(36);default:''"`
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
QuestionCount int `json:"question_count" gorm:"default:0"`
CreatorID string `json:"creator_id" gorm:"type:varchar(36);default:''"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"-" gorm:"index"`
}
// TableName pins the physical table name.
@@ -1008,8 +1077,24 @@ const (
// RuleKeyRoleDict 职称角色字典:{"roles":[{key,label,short,system,inherits[]}]}。
// 5 个系统角色为默认;自定义角色经 inherits 分配权限组(见 TrainingRoleDef)。
RuleKeyRoleDict = "role_dict"
// RuleKeyCourseCategoryDict 课程分类字典:{"categories":[...]}(课程管理
// 筛选与表单下拉选项,配置中心「课程分类」卡维护,预设之外支持手动输入)。
RuleKeyCourseCategoryDict = "course_category_dict"
)
// DefaultCourseCategories 课程分类默认字典(与 defaultRuleSeed 的
// course_category_dict、前端 DEFAULT_COURSE_CATEGORIES 一致)。
func DefaultCourseCategories() []string {
return []string{
"专业技能类",
"企业文化与制度类",
"通用技能类",
"安全与健康类",
"管理领导类",
"行业与产品知识类",
}
}
// TrainingRuleConfig 规则配置(业务规则改配置不改代码)。
type TrainingRuleConfig struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
@@ -1032,6 +1117,7 @@ func (TrainingRuleConfig) TableName() string { return "tr_rule_configs" }
const (
TrainingTemplateDemandCollection = "demand_collection" // 年度教育培训收集模板.xls
TrainingTemplateQuestionBank = "question_bank" // 部门培训课程试题(题库导入版)模板.xlsx
TrainingTemplateCourseLibrary = "course_library" // 课程管理导入模板.xlsx
)
// TrainingTemplate 租户自定义导入模板(配置中心上传,覆盖内置默认)。