fix(培训优化):1.签到码文案改「二维码有效期至 HH:mm」、代扫码按钮改「补录」;2.课程管理「适合人员」升级「课程权限」(默认所属部门,部门+人员混合选择互斥,按权限过滤目录/选课/学员视图);3.筛选增加按状态查询,核验改审核;4.审核通过即自动发布(去发布按钮),审核时课程权限必填;5.下线课程全面拦截(和信课程撤回/计划不可选/学习提示已下线,存量计划保留);6.课件管理支持多课件追加不替换(迁移000163/000164);7.AI对话问候语改「小和」;8.登录页品牌标识提升对比度
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s

This commit is contained in:
runny committed 2026-11-26 10:20:12 +08:00
1 parent 9e00af1905
commit 6defb1f2c6
22 files changed
+1169 -307

No files matched your search

@@ -13,6 +13,36 @@ import (
// 月培训计划的「计划名称」从本表选择,选中后经 tr_courses.library_course_id 关联。
// ---------------------------------------------------------------------------
// courseLibraryPermissionMatchSQL 课程权限覆盖判定(000163):
// - perm_dept_ids 含调用方部门 id,或 perm_user_ids 含调用方用户 id → 可见;
// - perm 两列为空的存量课程沿用 suitable_members 老口径:'全部' 全员可见 /
// 部门名成员匹配(逗号/分号归一为「、」)/ 所属部门兜底(空=全员)。
//
// 参数顺序:PermDeptID×2, PermUserID×2, '全部', 调用方部门名×2, 调用方部门 id×2。
const courseLibraryPermissionMatchSQL = "tr_course_library.perm_dept_ids <> '' AND ? <> '' AND ? = ANY(string_to_array(tr_course_library.perm_dept_ids, ',')) " +
"OR tr_course_library.perm_user_ids <> '' AND ? <> '' AND ? = ANY(string_to_array(tr_course_library.perm_user_ids, ',')) " +
"OR (tr_course_library.perm_dept_ids = '' AND tr_course_library.perm_user_ids = '' AND (" +
"tr_course_library.suitable_members = ? " +
"OR (? <> '' AND ? = ANY(string_to_array(replace(replace(replace(replace(tr_course_library.suitable_members, ',', '、'), ',', '、'), ';', '、'), ';', '、'), '、'))) " +
"OR (tr_course_library.suitable_members = '' AND (tr_course_library.owner_dept_id = '' " +
"OR (? <> '' AND tr_course_library.owner_dept_id = ?))))"
// courseLibraryPermissionCond 组装课程权限匹配条件与参数(000163;handler 注入
// 调用方部门 id/部门名/用户 id,PermIncludeCreator 时创建人/讲师放行)。
func courseLibraryPermissionCond(q *interfaces.TrainingListQuery) (string, []interface{}) {
cond := courseLibraryPermissionMatchSQL
args := []interface{}{
q.PermDeptID, q.PermDeptID,
q.PermUserID, q.PermUserID,
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID,
}
if q.PermIncludeCreator {
cond += " OR (tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?)"
args = append(args, q.PermUserID, q.PermUserID)
}
return "(" + cond + ")", args
}
// 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) {
@@ -31,20 +61,23 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
if q.RelatedUserID != "" {
tx = tx.Where("tr_course_library.creator_id = ? OR tr_course_library.lecturer_id = ?", q.RelatedUserID, q.RelatedUserID)
}
// 学员目录口径(000160,scope=catalog):仅已发布 + 适合人员覆盖调用方。
// suitable='全部' 全员可见;000159 多部门口径:值按「、」拆分(逗号/分号
// 兼容归一)后与调用方部门名做成员匹配;未设置适合人员的存量课程沿用
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。调用方
// 无部门档案时只见「全部」与未设置的课程。
// 学员目录口径(000160,scope=catalog):仅已发布 + 课程权限覆盖调用方
// (000163:perm 两列精确命中;存量课程沿用 suitable_members 老口径)。
if q.CatalogOnly {
tx = tx.Where("tr_course_library.publish_status = ?", "published")
tx = tx.Where(
"tr_course_library.suitable_members = ? "+
"OR (? <> '' AND ? = ANY(string_to_array(replace(replace(replace(replace(tr_course_library.suitable_members, ',', '、'), ',', '、'), ';', '、'), ';', '、'), '、'))) "+
"OR (tr_course_library.suitable_members = '' AND (tr_course_library.owner_dept_id = '' "+
"OR (? <> '' AND tr_course_library.owner_dept_id = ?)))",
"全部", q.CatalogDeptName, q.CatalogDeptName, q.CatalogDeptID, q.CatalogDeptID,
)
cond, args := courseLibraryPermissionCond(q)
tx = tx.Where(cond, args...)
}
// 课程权限过滤(000163):计划选课/无维护角色视图按调用方部门+人员收窄
// (与 catalog 同一匹配口径,handler 按视图注入调用方身份与放行项)。
if q.PermFilter {
cond, args := courseLibraryPermissionCond(q)
tx = tx.Where(cond, args...)
}
// 计划选课口径(000163,scope=plan):已下线课程不再可选(存量计划行
// tr_courses 不受影响,历史计划照常展示)。
if q.ExcludeOffline {
tx = tx.Where("tr_course_library.publish_status <> ?", "offline")
}
}
var total int64
@@ -103,6 +136,26 @@ func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID
return &item, nil
}
// ListCourseLibraryStatuses 批量取课程管理条目的发布状态(000163:月培训计划
// 列表/学习页据此拦截「该课程已下线」;ids 为 tr_courses.library_course_id 集合)。
func (r *trainingRepository) ListCourseLibraryStatuses(ctx context.Context, tenantID uint64, ids []string) (map[string]string, error) {
out := make(map[string]string, len(ids))
if len(ids) == 0 {
return out, nil
}
var rows []*types.TrainingCourseLibrary
if err := r.db.WithContext(ctx).
Select("id, publish_status").
Where("tenant_id = ? AND id IN ?", tenantID, ids).
Find(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
out[row.ID] = row.PublishStatus
}
return out, 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
@@ -118,6 +171,9 @@ func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *
"owner_dept_id": item.OwnerDeptID,
"description": item.Description,
"suitable_members": item.SuitableMembers,
// 课程权限(000163):部门/人员 id 列表随保存更新。
"perm_dept_ids": item.PermDeptIDs,
"perm_user_ids": item.PermUserIDs,
"category": item.Category,
"type": item.Type,
"mode": item.Mode,
@@ -130,6 +186,8 @@ func (r *trainingRepository) UpdateCourseLibraryItem(ctx context.Context, item *
"file_size": item.FileSize,
// 课件知识库文档 id(上传同步后回填;code 编号列只读不在更新列)。
"knowledge_id": item.KnowledgeID,
// 课件列表(000164 多课件,JSON 数组;主字段镜像最新条)。
"materials": item.Materials,
// 核验状态(000157):编辑/换课件后由服务层重置为待核验并清空核验痕迹。
"verify_status": item.VerifyStatus,
"confirmed_by": item.ConfirmedBy,
@@ -57,9 +57,42 @@ func (s *trainingService) ListCourses(ctx context.Context, tenantID uint64, q *i
c.ExamStatus = courseExamStatus(c.ExpectedCount, st)
}
}
// 关联课程管理条目的发布状态(000163):月培训计划列表标注「课程已下线」。
s.attachLibraryOffline(ctx, tenantID, courses...)
return courses, total, nil
}
// attachLibraryOffline 批量回填课程关联课程管理条目的发布状态(000163):
// library_course_id 命中的条目已下线(publish_status=offline)时置
// LibraryOffline,学习入口按「该课程已下线」拦截(存量计划行保留不消失)。
// fail-open:查询失败保持零值,不阻断列表/详情。
func (s *trainingService) attachLibraryOffline(ctx context.Context, tenantID uint64, courses ...*types.TrainingCourse) {
ids := make([]string, 0, len(courses))
hit := make(map[string]bool, len(courses))
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" || hit[c.LibraryCourseID] {
continue
}
hit[c.LibraryCourseID] = true
ids = append(ids, c.LibraryCourseID)
}
if len(ids) == 0 {
return
}
statuses, err := s.repo.ListCourseLibraryStatuses(ctx, tenantID, ids)
if err != nil {
logger.Warnf(ctx, "Skip attach library offline status, tenant=%d error: %v", tenantID, err)
return
}
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" {
continue
}
c.LibraryPublishStatus = statuses[c.LibraryCourseID]
c.LibraryOffline = c.LibraryPublishStatus == "offline"
}
}
// courseLearnStatus 课程学习状态:
// 无人签到且无人开始学习 → 未学习;完成人数(签到∪任务done)达到
// max(应到, 参与) → 已学习;否则 → 学习中。线下课签到即视同完成学习。
@@ -126,6 +159,9 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil {
course.ExamReady = true
}
// 关联课程管理条目已下线时带出标记(000163):学习页据此提示
// 「该课程已下线」并拦截课件/考试入口。
s.attachLibraryOffline(ctx, tenantID, course)
return course, nil
}
+2 -2
View File
@@ -222,8 +222,8 @@ func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64,
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
if err != nil {
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
// 材料行不存在时按课程管理条目取文件流,与发布/学习链路同口径。
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID); libErr == nil {
// 材料行不存在时按课程管理条目取文件流(最新课件条目),与发布/学习链路同口径。
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID, ""); libErr == nil {
return rc, fileName, nil
}
return nil, "", werrors.NewNotFoundError("课件不存在")
+190 -66
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -55,6 +56,13 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
item.LecturerID = strings.TrimSpace(item.LecturerID)
item.LecturerExternal = strings.TrimSpace(item.LecturerExternal)
item.MaterialName = strings.TrimSpace(item.MaterialName)
// 课程权限(000163):部门/人员 id 列表归一为「,」连接(去空白去重)。
item.PermDeptIDs = normalizePermIDs(item.PermDeptIDs)
item.PermUserIDs = normalizePermIDs(item.PermUserIDs)
// 课件列表(000164 多课件):新建/导入无课件时落空数组列默认值(非 NULL)。
if len(item.Materials) == 0 {
item.Materials = types.JSON([]byte("[]"))
}
if item.Type != "elective" {
item.Type = "required"
}
@@ -64,6 +72,51 @@ func normalizeCourseLibrary(item *types.TrainingCourseLibrary) error {
return nil
}
// normalizePermIDs 课程权限 id 列表归一(000163):逗号/顿号/空白分隔 → 去空白
// 去重 → 「,」连接落库(与 string_to_array(x, ',') 匹配口径一致)。
func normalizePermIDs(raw string) string {
seen := make(map[string]bool)
out := make([]string, 0, 8)
for _, part := range strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == ',' || r == '、' || r == ' ' || r == ';' || r == ';'
}) {
id := strings.TrimSpace(part)
if id == "" || seen[id] {
continue
}
seen[id] = true
out = append(out, id)
}
return strings.Join(out, ",")
}
// setCourseMaterials 序列化课件条目列表回 JSON 列(000164 多课件)。
func setCourseMaterials(item *types.TrainingCourseLibrary, list []types.CourseLibraryMaterial) {
if len(list) == 0 {
item.Materials = types.JSON([]byte("[]"))
return
}
buf, err := json.Marshal(list)
if err != nil {
logger.Warnf(context.Background(), "Marshal course library materials failed, course=%s error: %v", item.ID, err)
return
}
item.Materials = types.JSON(buf)
}
// refreshPrimaryFromMaterials 主字段镜像(000164 多课件):file_key/file_name/
// file_size/knowledge_id 恒指向最新一条课件条目(发布校验/AI 出题/学习抽屉/
// 月计划带出等既有依赖口径不变);列表清空后主字段一并清空。
func refreshPrimaryFromMaterials(item *types.TrainingCourseLibrary) {
list := item.CourseMaterialList()
if len(list) == 0 {
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = "", "", 0, ""
return
}
latest := list[len(list)-1]
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = latest.FileKey, latest.Name, latest.Size, latest.KnowledgeID
}
// ListCourseLibraryItems 课程管理列表(月培训计划「计划名称」下拉同源)。
func (s *trainingService) ListCourseLibraryItems(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error) {
return s.repo.ListCourseLibrary(ctx, tenantID, q)
@@ -126,21 +179,17 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
if err != nil || old == nil {
return nil, werrors.NewNotFoundError("课程不存在")
}
// 课件文件:移除标记强制清空;未重新上传时保留原文件信息
// (表单不回传 file_key,零值会被误清)。
// 课件列表(000164 多课件)不随表单回传:编辑保存保持原列表;课件文件字段
// 由列表镜像刷新(原 file_key 零值误清保护收敛到镜像逻辑;ClearFile 移除
// 标记保留兼容,置 true 时整体清空课件)。
item.Materials = old.Materials
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
setCourseMaterials(item, nil)
}
refreshPrimaryFromMaterials(item)
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
item.OwnerDeptID = old.OwnerDeptID
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
// 编辑即回待审核(000157):内容变更后原审核结论作废,需重新审核。
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
@@ -192,17 +241,24 @@ func (s *trainingService) SetCourseLibraryPublishStatus(ctx context.Context, ten
if status == "published" && item.VerifyStatus != types.CourseLibraryVerifyConfirmed {
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未核验,请先由所属部门课长/经理核验确认后再发布", item.Name))
}
if status == "published" && strings.TrimSpace(item.FileKey) == "" && strings.TrimSpace(item.KnowledgeID) == "" {
if status == "published" && !item.HasCourseMaterial() {
return werrors.NewBadRequestError(fmt.Sprintf("课程《%s》尚未上传课件,请先在列表「课件」入口上传课件文件(或从知识库选择)后再发布", item.Name))
}
return s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, status)
}
// VerifyCourseLibraryItems 批量核验课程条目(000157,单个/批量共用):核验人所在
// 部门(deptScope,handler 保证恒非空)必须与课程所属部门一致;已确认行与部门
// 不匹配行跳过,返回实际核验数与跳过数,全无效时报错提示。
func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (int64, int64, error) {
// VerifyCourseLibraryItems 批量审核课程条目(000163:核验升级为「审核」,审核
// 通过即自动发布;单个/批量共用):审核人所在部门(deptScope,handler 保证恒
// 非空)必须与课程所属部门一致;已确认行与部门不匹配行跳过。
// 审核前置(测试反馈 2026-11-26):课程权限必填 —— perm 两列与存量 suitable_members
// 均为空的课程拒绝审核,整批报错定位到具体课程。
// 审核通过后:已有课件(原始文件或知识库挂接)的课程同步置为已发布,无需再点
// 「发布」;未上传课件的课程保持待发布,上传课件重新审核后自动发布。
func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (*interfaces.CourseLibraryVerifyResult, error) {
result := &interfaces.CourseLibraryVerifyResult{UnpublishedNames: []string{}}
allowed := make([]string, 0, len(ids))
// 可自动发布(审核通过 + 已传课件)与待补课件(审核通过未传课件)分桶。
publishable := make([]string, 0, len(ids))
for _, id := range ids {
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, id)
if err != nil || item == nil {
@@ -212,20 +268,42 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
continue // 已确认行幂等跳过
}
if deptScope != "" && item.OwnerDeptID != deptScope {
continue // 课长/经理仅可核验本部门课程
continue // 课长/经理仅可审核本部门课程
}
// 课程权限必填(审核前置):权限两列与存量适合人员均未设置时拦截。
if !item.HasPermissionSet() {
return nil, werrors.NewBadRequestError(
fmt.Sprintf("课程《%s》未设置课程权限,请先在课程管理中设置课程权限后再审核", item.Name))
}
allowed = append(allowed, id)
if item.HasCourseMaterial() {
publishable = append(publishable, id)
} else {
result.UnpublishedNames = append(result.UnpublishedNames, item.Name)
}
}
skipped := int64(len(ids) - len(allowed))
result.Skipped = int64(len(ids) - len(allowed))
if len(allowed) == 0 {
return 0, skipped, werrors.NewBadRequestError("没有可核验的课程(仅本部门待核验状态的课程可核验)")
return nil, werrors.NewBadRequestError("没有可审核的课程(仅本部门待审核状态的课程可审核)")
}
verified, err := s.repo.ConfirmCourseLibraryItems(ctx, tenantID, allowed, verifierID)
if err != nil {
return 0, 0, err
return nil, err
}
logger.Infof(ctx, "[Training] course library verified, tenant=%d verified=%d skipped=%d verifier=%s", tenantID, verified, skipped, verifierID)
return verified, skipped, nil
result.Verified = verified
// 审核即发布(000163):已传课件的条目同步置为已发布,培训中心「和信课程」
// 与月/年培训计划选课立即可见(按课程权限)。发布失败不回滚审核,仅记日志。
if len(publishable) > 0 {
for _, id := range publishable {
if perr := s.repo.UpdateCourseLibraryPublishStatus(ctx, tenantID, id, "published"); perr != nil {
logger.Warnf(ctx, "Auto publish after course verify failed, tenant=%d course=%s error: %v", tenantID, id, perr)
continue
}
result.AutoPublished++
}
}
logger.Infof(ctx, "[Training] course library verified&published, tenant=%d verified=%d skipped=%d auto_published=%d verifier=%s", tenantID, result.Verified, result.Skipped, result.AutoPublished, verifierID)
return result, nil
}
// matchOrCreateLibraryCourse 需求侧课程校验(000158):按课程名称在课程管理精准
@@ -262,6 +340,7 @@ func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenant
PublishStatus: "draft",
VerifyStatus: types.CourseLibraryVerifyPending,
CreatorID: creatorID,
Materials: types.JSON([]byte("[]")),
}
if item.LecturerID != "" {
item.LecturerExternal = ""
@@ -363,8 +442,11 @@ func (s *trainingService) ExportCourseLibrary(ctx context.Context, tenantID uint
return filename, buf.Bytes(), nil
}
// UploadCourseLibraryMaterial 上传课件原始文件(fileSvc 落 file_key,不入知识库
// 解析链路;名称登记与文件可并存)。
// UploadCourseLibraryMaterial 上传课件原始文件(000164 多课件:追加课件条目,
// 不再替换既有课件)。fileSvc 落 file_key,不入知识库解析链路;文档类同步知识库
// 「企业培训(课件)」(000153:AI 出题与对话问答依赖知识库分块;视频类仅存原始
// 文件,同步失败 fail-open 退回原始文件存取)。主字段(file_*/knowledge_id)镜像
// 最新一条,发布校验/AI 出题/学习抽屉等既有依赖口径不变;课件变更即回待审核。
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("缺少上传文件")
@@ -378,11 +460,14 @@ func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenan
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,退回原始文件存取。
entry := types.CourseLibraryMaterial{
Mid: trainingNewID(),
Name: fh.Filename,
Size: fh.Size,
FileKey: fileKey,
Origin: "upload",
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
if !isVideoMaterialFile("", fh.Filename) {
coursewareKB, _, kbErr := s.ensureTrainingKnowledgeBases(ctx)
if kbErr != nil {
@@ -390,80 +475,114 @@ func (s *trainingService) UploadCourseLibraryMaterial(ctx context.Context, tenan
} 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
entry.KnowledgeID = knowledgeID
}
} else {
item.KnowledgeID = ""
}
// 名称登记为空时以文件名兜底,便于列表直接识别课件。
// 追加课件条目(不替换),主字段镜像为最新条;名称登记为空时以首个文件名兜底。
setCourseMaterials(item, append(item.CourseMaterialList(), entry))
refreshPrimaryFromMaterials(item)
if strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = fh.Filename
}
// 换课件即回待核验(000157):课件内容变更后需重新核验。
// 换课件即回待审核(000157):课件内容变更后需重新审核。
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
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)
logger.Infof(ctx, "[Training] course library material appended, tenant=%d course=%s materials=%d size=%d uploader=%s", tenantID, id, len(item.CourseMaterialList()), 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) {
// GetCourseLibraryMaterialFile 流式取回课件原始文件(000164:mid 定位具体课件
// 条目,空 = 最新一条兼容旧调用):文档类优先按知识库文档取回流(000153 同步入库
// 后与月计划课件同口径),视频/同步失败回退 file_key。
func (s *trainingService) GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id, mid 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 == "" {
entry := item.PrimaryCourseMaterial()
if mid != "" {
entry = nil
for i := range item.CourseMaterialList() {
if item.CourseMaterialList()[i].Mid == mid {
entry = &item.CourseMaterialList()[i]
break
}
}
}
if entry == nil || (entry.FileKey == "" && entry.KnowledgeID == "") {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
}
if item.KnowledgeID != "" {
rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, item.KnowledgeID)
if entry.KnowledgeID != "" {
rc, _, err := s.knowledgeSvc.GetKnowledgeFile(ctx, entry.KnowledgeID)
if err == nil {
// 下载文件名沿用登记名(知识库文档名可能与登记名不一致)。
return rc, item.FileName, nil
// 下载文件名沿用条目名(知识库文档名可能与登记名不一致)。
return rc, entry.Name, nil
}
logger.Warnf(ctx, "Fallback to raw file for course library material, course: %s, error: %v", id, err)
}
if item.FileKey == "" {
if entry.FileKey == "" {
return nil, "", werrors.NewNotFoundError("该课程未上传课件文件")
}
rc, err := s.fileSvc.GetFile(ctx, item.FileKey)
rc, err := s.fileSvc.GetFile(ctx, entry.FileKey)
if err != nil {
return nil, "", err
}
return rc, item.FileName, nil
return rc, entry.Name, nil
}
// RemoveCourseLibraryMaterial 移除课程课件原始文件/知识库挂接(名称登记保留,
// 上传课件时仍会以文件名兜底名称登记):文件与知识库文档字段清空,课件内容
// 变更即回待核验(000157 同口径),移除后课程不满足发布课件前置。
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error) {
// RemoveCourseLibraryMaterial 移除课件条目(000164 多课件:按 mid 定位,mid 空 =
// 移除最新一条兼容旧调用):文件与知识库挂接随条目移除,名称登记保留;主字段镜像
// 回退为剩余最新条(无剩余则清空);课件变更即回待审核(000157 同口径)。未跑
// 000164 回填的存量行(列表为空而主字段有课件)按清空主字段兜底。
func (s *trainingService) RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, mid, updaterID string) (*types.TrainingCourseLibrary, 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.NewBadRequestError("该课程未上传课件文件,无需移除")
list := item.CourseMaterialList()
if len(list) == 0 {
if item.FileKey == "" && item.KnowledgeID == "" {
return nil, werrors.NewBadRequestError("该课程未上传课件文件,无需移除")
}
// 存量行兜底:课件列表为空时按清空主字段处理(旧口径)。
item.FileKey, item.FileName, item.FileSize, item.KnowledgeID = "", "", 0, ""
} else {
idx := -1
if mid == "" {
idx = len(list) - 1
} else {
for i := range list {
if list[i].Mid == mid {
idx = i
break
}
}
}
if idx < 0 {
return nil, werrors.NewNotFoundError("课件条目不存在或已移除")
}
removed := list[idx]
list = append(list[:idx], list[idx+1:]...)
setCourseMaterials(item, list)
refreshPrimaryFromMaterials(item)
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s material=%s operator=%s", tenantID, id, removed.Mid, updaterID)
}
item.FileKey, item.FileName, item.FileSize = "", "", 0
item.KnowledgeID = ""
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
if err := s.repo.UpdateCourseLibraryItem(ctx, item); err != nil {
return nil, err
}
logger.Infof(ctx, "[Training] course library material removed, tenant=%d course=%s operator=%s", tenantID, id, updaterID)
return item, nil
}
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择已有
// 文档作为课程课件(与上传同步同口径:下载/月计划课件挂接/AI 出题共用 knowledge_id)。
// 原始文件字段清空,名称登记为空时以文档名兜底。
// 文档作为课程课件(000164 多课件:追加条目,不替换;与上传同口径,下载/月计划
// 课件挂接/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 == "" {
@@ -481,21 +600,26 @@ func (s *trainingService) AttachCourseLibraryMaterialFromKnowledge(ctx context.C
if name == "" {
name = strings.TrimSpace(doc.Title)
}
if name != "" {
item.FileName = name
if strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = name
}
entry := types.CourseLibraryMaterial{
Mid: trainingNewID(),
Name: name,
Size: doc.FileSize,
KnowledgeID: knowledgeID,
Origin: "kb",
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
item.FileKey, item.FileSize = "", 0
item.KnowledgeID = knowledgeID
// 换课件即回待核验(000157):课件内容变更后需重新核验。
setCourseMaterials(item, append(item.CourseMaterialList(), entry))
refreshPrimaryFromMaterials(item)
if name != "" && strings.TrimSpace(item.MaterialName) == "" {
item.MaterialName = name
}
// 换课件即回待审核(000157):课件内容变更后需重新审核。
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
item.ConfirmedAt = nil
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)
logger.Infof(ctx, "[Training] course library material attached from knowledge base, tenant=%d course=%s knowledge=%s materials=%d operator=%s", tenantID, id, knowledgeID, len(item.CourseMaterialList()), updaterID)
return item, nil
}
@@ -2,6 +2,7 @@ package service
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"strings"
@@ -98,7 +99,7 @@ func TestRemoveCourseLibraryMaterial(t *testing.T) {
}
seedCourseLibraryItem(t, db, tenantID, item)
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op")
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "", "u-op")
require.NoError(t, err)
require.Empty(t, updated.FileKey)
require.Empty(t, updated.FileName)
@@ -117,7 +118,7 @@ func TestRemoveCourseLibraryMaterial(t *testing.T) {
require.Equal(t, types.CourseLibraryVerifyPending, stored.VerifyStatus)
// 已无课件再移除:拒绝。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "u-op")
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, item.ID, "", "u-op")
require.Error(t, err)
}
@@ -126,6 +127,93 @@ func timeNowPtr() *time.Time {
return &v
}
// 审核(000163:核验升级为审核,审核通过即自动发布):
// - 课程权限必填:perm 两列与 suitable_members 均为空的课程整批拒绝;
// - 已传课件的课程审核通过即自动发布(published);
// - 未传课件的课程仅确认通过、不发布,回传课程名提示补传。
func TestVerifyCourseLibraryItemsRequiresPermissionAndAutoPublish(t *testing.T) {
svc, db, tenantID := newCourseLibraryFixture(t)
ctx := context.Background()
noPerm := &types.TrainingCourseLibrary{ID: "cl-noperm", Name: "未设置权限课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, FileKey: "fk-1", FileName: "a.pptx"}
permAndFile := &types.TrainingCourseLibrary{ID: "cl-ok", Name: "权限加课件课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-1", FileKey: "fk-2", FileName: "b.pptx"}
permNoFile := &types.TrainingCourseLibrary{ID: "cl-nofile", Name: "权限缺课件课程", OwnerDeptID: "dept-1", VerifyStatus: types.CourseLibraryVerifyPending, SuitableMembers: "全部"}
otherDept := &types.TrainingCourseLibrary{ID: "cl-other", Name: "别部门课程", OwnerDeptID: "dept-2", VerifyStatus: types.CourseLibraryVerifyPending, PermDeptIDs: "dept-2"}
for _, item := range []*types.TrainingCourseLibrary{noPerm, permAndFile, permNoFile, otherDept} {
seedCourseLibraryItem(t, db, tenantID, item)
}
// 课程权限未设置:整批拒绝并点名课程。
_, err := svc.VerifyCourseLibraryItems(ctx, tenantID, []string{noPerm.ID}, "u-verifier", "dept-1")
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "课程权限"), "应提示未设置课程权限,实际: %s", err.Error())
// 部门不匹配:跳过,无可用条目报错。
_, err = svc.VerifyCourseLibraryItems(ctx, tenantID, []string{otherDept.ID}, "u-verifier", "dept-1")
require.Error(t, err)
// 混合批次:权限+课件 → 确认并自动发布;权限缺课件 → 仅确认不发布。
res, err := svc.VerifyCourseLibraryItems(ctx, tenantID, []string{permAndFile.ID, permNoFile.ID, otherDept.ID}, "u-verifier", "dept-1")
require.NoError(t, err)
require.EqualValues(t, 2, res.Verified)
require.EqualValues(t, 1, res.Skipped)
require.EqualValues(t, 1, res.AutoPublished)
require.Equal(t, []string{"权限缺课件课程"}, res.UnpublishedNames)
stored, err := svc.GetCourseLibraryItem(ctx, tenantID, permAndFile.ID)
require.NoError(t, err)
require.Equal(t, types.CourseLibraryVerifyConfirmed, stored.VerifyStatus)
require.Equal(t, "published", stored.PublishStatus)
storedNoFile, err := svc.GetCourseLibraryItem(ctx, tenantID, permNoFile.ID)
require.NoError(t, err)
require.Equal(t, types.CourseLibraryVerifyConfirmed, storedNoFile.VerifyStatus)
require.Equal(t, "draft", storedNoFile.PublishStatus)
}
// 多课件(000164):课件列表追加不替换,主字段镜像最新条;按 mid 移除后主字段
// 回退为剩余最新条,全部移除后主字段清空,再移除报错。
func TestCourseLibraryMultiMaterialsRemoveByMid(t *testing.T) {
svc, db, tenantID := newCourseLibraryFixture(t)
ctx := context.Background()
m1 := types.CourseLibraryMaterial{Mid: "m-1", Name: "a.pptx", Size: 1, FileKey: "fk-1", Origin: "upload"}
m2 := types.CourseLibraryMaterial{Mid: "m-2", Name: "b.docx", Size: 2, KnowledgeID: "kb-2", Origin: "kb"}
buf, err := json.Marshal([]types.CourseLibraryMaterial{m1, m2})
require.NoError(t, err)
seed := &types.TrainingCourseLibrary{
ID: "cl-multi", Name: "多课件课程", OwnerDeptID: "dept-1",
Materials: types.JSON(buf),
// 主字段镜像最新条 m-2。
FileKey: "", FileName: "b.docx", FileSize: 2, KnowledgeID: "kb-2",
VerifyStatus: types.CourseLibraryVerifyPending,
}
seedCourseLibraryItem(t, db, tenantID, seed)
// 按 mid 移除首条:剩余最新条 b.docx 镜像到主字段。
updated, err := svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-1", "u-op")
require.NoError(t, err)
require.Len(t, updated.CourseMaterialList(), 1)
require.Equal(t, "m-2", updated.CourseMaterialList()[0].Mid)
require.Equal(t, "kb-2", updated.KnowledgeID)
require.Equal(t, "b.docx", updated.FileName)
require.Equal(t, types.CourseLibraryVerifyPending, updated.VerifyStatus)
// 移除不存在的 mid:报错不误删。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-x", "u-op")
require.Error(t, err)
// 移除最后一条:列表清空、主字段一并清空。
updated, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "m-2", "u-op")
require.NoError(t, err)
require.Empty(t, updated.CourseMaterialList())
require.Empty(t, updated.FileKey)
require.Empty(t, updated.KnowledgeID)
// 已无课件再移除:报错。
_, err = svc.RemoveCourseLibraryMaterial(ctx, tenantID, "cl-multi", "", "u-op")
require.Error(t, err)
}
// 计划「形式」与课程「线上/线下」独立(000162):绑定带出名称/类型,不覆盖
// 计划侧 mode——课程线下 + 计划线上、课程线上 + 计划线下双向保持请求值。
func TestApplyLibraryCourseBindingKeepsPlanMode(t *testing.T) {
+88 -18
View File
@@ -29,9 +29,13 @@ type saveCourseLibraryRequest struct {
OwnerDeptID string `json:"owner_dept_id"`
// OwnerDeptName 所属部门名(导入兜底:前端未匹配到部门 id 时只传名,
// 服务端按组织架构名册解析;与只读展示列 owner_dept_name 同名字段复用)。
OwnerDeptName string `json:"owner_dept_name"`
Description string `json:"description"`
SuitableMembers string `json:"suitable_members"`
OwnerDeptName string `json:"owner_dept_name"`
Description string `json:"description"`
SuitableMembers string `json:"suitable_members"`
// PermDeptIDs/PermUserIDs 课程权限(000163):可见部门/人员 id 列表(逗号
// 分隔);两者与 suitable_members 同时为空的存量课程沿用老口径。
PermDeptIDs string `json:"perm_dept_ids"`
PermUserIDs string `json:"perm_user_ids"`
Category string `json:"category"`
Type string `json:"type"`
Mode string `json:"mode"`
@@ -52,6 +56,8 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
OwnerDeptName: req.OwnerDeptName,
Description: req.Description,
SuitableMembers: req.SuitableMembers,
PermDeptIDs: req.PermDeptIDs,
PermUserIDs: req.PermUserIDs,
Category: req.Category,
Type: req.Type,
Mode: req.Mode,
@@ -66,16 +72,21 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护
// scope=catalog(000160)为学员目录口径:已发布 + 课程权限覆盖调用方
// (000163:perm 部门/人员 id 命中;存量课程沿用适合人员老口径),不按维护
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
// scope=plan(000163)创建月度计划选课口径:已下线课程不再可选;课程权限
// 覆盖调用方(人事作为培训管理员不受权限收窄,课程创建人/讲师放行);
// 纯学员/无维护角色调用方保持原数据范围,不放大数据可见性。
func (h *Handler) ListCourseLibrary(c *gin.Context) {
q := listQueryFromRequest(c)
if q.Scope == "catalog" {
q.CatalogOnly = true
// 调用方部门(id+名)用于适合人员匹配;无培训档案的调用方两个字段
// 留空(仅见「全部」与未设置适合人员的课程),不阻断目录查询。
// 课程权限匹配身份(000163):调用方部门(id+名)+用户 id;无培训档案
// 的调用方部门字段留空(仅见「全部」与未设置权限的课程),不阻断目录。
q.PermUserID = callerUserID(c)
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID
}
if q.CatalogDeptID != "" {
@@ -96,8 +107,49 @@ func (h *Handler) ListCourseLibrary(c *gin.Context) {
return
}
q.DeptID, q.RelatedUserID = "", ""
// 已下线课程不能再被计划选用(存量计划行不受影响)。
q.ExcludeOffline = true
// 课程权限收窄(000163):人事(培训管理员)不受限;课长/经理/讲师仅可
// 选择权限覆盖本人部门/本人(或本人创建/授课)的课程。
if !h.callerHasTrainingRole(c, types.TrainingRoleHR) {
q.PermFilter = true
q.PermIncludeCreator = true
q.PermUserID = callerUserID(c)
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
}
} else {
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
// 课程权限收窄(000163):课程管理页对无维护角色的调用方(讲师/学员
// 「与我相关」口径)叠加课程权限过滤;维护角色(人事/课长/经理)保持
// 全量管理可见性 —— 审核按所属部门授权,不能被权限选择挡住。
if q.RelatedUserID != "" {
q.PermFilter = true
q.PermIncludeCreator = true
q.PermUserID = q.RelatedUserID
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.PermDeptID = member.DeptID
q.CatalogDeptID = member.DeptID
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
}
}
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q)
if err != nil {
@@ -107,6 +159,17 @@ func (h *Handler) ListCourseLibrary(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
}
// callerHasTrainingRole 调用方是否具备指定培训角色(roles 已按权限组展开,
// 经理经课长继承自动命中)。
func (h *Handler) callerHasTrainingRole(c *gin.Context, want types.TrainingRole) bool {
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil || member == nil {
return false
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
return types.HasTrainingRole(roles, want)
}
// SaveCourseLibraryItem POST /training/course-library — 新增/编辑(id 空 = 新增)。
// 维护角色限人事/课长/讲师;无维护角色的用户兜底仅可编辑「与我相关」课程
// (本人创建或本人授课,不可新增,000157)。
@@ -215,14 +278,15 @@ func (h *Handler) callerVerifyDeptScope(c *gin.Context) (deptID string, ok bool)
}
// verifyCourseLibraryRequest is the body of POST /training/course-library/verify
// (单个/批量核验共用,ids 长度 1 即单条)。
// (单个/批量审核共用,ids 长度 1 即单条)。
type verifyCourseLibraryRequest struct {
IDs []string `json:"ids" binding:"required,min=1"`
}
// VerifyCourseLibraryItems POST /training/course-library/verify — 课程条目核验
// (000157):仅本部门课长/经理可核验(人事/讲师/学员/空间管理员均无跨部门核验权),
// 待核验 → 已确认;越权/已确认/不存在行跳过不阻断其余行。
// VerifyCourseLibraryItems POST /training/course-library/verify — 课程条目审核
// (000163:核验升级为审核,审核通过即自动发布):仅本部门课长/经理可审核
// (人事/讲师/学员/空间管理员均无跨部门审核权),待审核 → 已确认 + 自动发布;
// 课程权限未设置整批拒绝;越权/已确认/不存在行跳过不阻断其余行。
func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleSupervisor, types.TrainingRoleManager) {
return
@@ -234,15 +298,15 @@ func (h *Handler) VerifyCourseLibraryItems(c *gin.Context) {
}
deptID, ok := h.callerVerifyDeptScope(c)
if !ok {
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可核验课程"))
_ = c.Error(errors.NewForbiddenError("仅本部门课长/经理可审核课程"))
return
}
verified, skipped, err := h.svc.VerifyCourseLibraryItems(c.Request.Context(), callerTenantID(c), req.IDs, callerUserID(c), deptID)
result, err := h.svc.VerifyCourseLibraryItems(c.Request.Context(), callerTenantID(c), req.IDs, callerUserID(c), deptID)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"verified": verified, "skipped": skipped}})
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
// ImportCourseLibraryRequest is the body of POST /training/course-library/import
@@ -343,12 +407,18 @@ func (h *Handler) AttachCourseLibraryMaterialFromKb(c *gin.Context) {
}
// RemoveCourseLibraryMaterial POST /training/course-library/:id/material/remove
// — 移除课程课件原始文件/知识库挂接(名称登记保留,课件变更即回待核验)。
// — 移除课件条目(000164 多课件:body 可选 {mid} 定位条目,缺省移除最新一条;
// 课件变更即回待审核)。
func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c))
// mid 可选(body 缺省/非 JSON 均按移除最新一条兼容旧调用,绑定错误忽略)。
var req struct {
Mid string `json:"mid"`
}
_ = c.ShouldBindJSON(&req)
item, err := h.svc.RemoveCourseLibraryMaterial(c.Request.Context(), callerTenantID(c), c.Param("id"), req.Mid, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
@@ -357,9 +427,9 @@ func (h *Handler) RemoveCourseLibraryMaterial(c *gin.Context) {
}
// CourseLibraryMaterialFile GET /training/course-library/:id/material/file —
// 课件原始文件流(下载/在线预览)。
// 课件原始文件流(下载/在线预览;query 可选 mid 定位课件条目,缺省最新一条)。
func (h *Handler) CourseLibraryMaterialFile(c *gin.Context) {
rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"))
rc, fileName, err := h.svc.GetCourseLibraryMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"), c.Query("mid"))
if err != nil {
_ = c.Error(err)
return
+37 -7
View File
@@ -10,6 +10,17 @@ import (
"academy/internal/types"
)
// CourseLibraryVerifyResult 课程审核结果(000163:审核即发布):Verified 实际
// 审核通过条数;Skipped 越权/已确认/不存在跳过条数;AutoPublished 审核通过且
// 已有课件、同步自动发布的条数;UnpublishedNames 审核通过但未上传课件、未自动
// 发布的课程名(需传课件后重新审核)。
type CourseLibraryVerifyResult struct {
Verified int64 `json:"verified"`
Skipped int64 `json:"skipped"`
AutoPublished int64 `json:"auto_published"`
UnpublishedNames []string `json:"unpublished"`
}
// TrainingListQuery 通用列表查询(分页 + 关键词 + 可选过滤维度)。
type TrainingListQuery struct {
Year int
@@ -36,6 +47,19 @@ type TrainingListQuery struct {
CatalogOnly bool
CatalogDeptID string
CatalogDeptName string
// 课程权限过滤(000163,handler 按视图口径注入):PermFilter 开启后,课程
// 权限两列(perm_dept_ids/perm_user_ids)非空的课程仅当调用方部门/用户命中
// 才可见;两列为空的存量课程沿用 suitable_members 口径(与 CatalogOnly 的
// 存量兜底一致)。PermDeptID/PermUserID 为调用方部门 id 与用户 id。
// PermIncludeCreator 计划选课等场景对课程创建人/讲师放行(本人维护的课程
// 不受权限选择限制)。
PermFilter bool
PermDeptID string
PermUserID string
PermIncludeCreator bool
// ExcludeOffline 计划选课口径(000163,scope=plan):已下线课程不再可选,
// 存量计划行(tr_courses)不受影响。
ExcludeOffline bool
}
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
@@ -99,6 +123,9 @@ type TrainingRepository interface {
// ---- 课程管理(课程资产主数据,月培训计划「计划名称」数据源) ----
ListCourseLibrary(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingCourseLibrary, int64, error)
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
// ListCourseLibraryStatuses 批量取课程条目发布状态(000163:学习入口拦截
// 已下线课程;ids 为 library_course_id 集合,返回 id → publish_status)。
ListCourseLibraryStatuses(ctx context.Context, tenantID uint64, ids []string) (map[string]string, error)
// FindCourseLibraryByName 按课程名称精准查找课程条目(000158 需求侧课程自动匹配)。
FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error)
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
@@ -338,9 +365,10 @@ type TrainingService interface {
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
// VerifyCourseLibraryItems 批量核验课程条目(000157,仅本部门课长/经理):
// deptScope 为调用方所在部门(恒非空),仅核验所属部门匹配的条目。
VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (verified int64, skipped int64, err error)
// VerifyCourseLibraryItems 批量审核课程条目(000163:核验升级为审核,审核
// 通过即自动发布;仅本部门课长/经理):deptScope 为调用方所在部门(恒非空),
// 仅审核所属部门匹配的条目;课程权限未设置的条目整批拒绝(审核前置)。
VerifyCourseLibraryItems(ctx context.Context, tenantID uint64, ids []string, verifierID, deptScope string) (*CourseLibraryVerifyResult, error)
// GetCourseLibraryItem 取单条课程条目(发布/下线后回显)。
GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error)
// DeleteCourseLibraryItem 软删课程条目(仅待核验状态可删;deptScope 非空时
@@ -352,13 +380,15 @@ type TrainingService interface {
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)
// GetCourseLibraryMaterialFile 流式取回课件原始文件(000164:mid 定位条目,
// 空 = 最新一条)。
GetCourseLibraryMaterialFile(ctx context.Context, tenantID uint64, id, mid string) (io.ReadCloser, string, error)
// AttachCourseLibraryMaterialFromKnowledge 从知识库「企业培训(课件)」选择
// 已有文档作为课程课件(与上传同步同口径)。
AttachCourseLibraryMaterialFromKnowledge(ctx context.Context, tenantID uint64, id, knowledgeID, updaterID string) (*types.TrainingCourseLibrary, error)
// RemoveCourseLibraryMaterial 移除课程课件(文件/知识库挂接清空,名称登记保留)。
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourseLibrary, error)
// RemoveCourseLibraryMaterial 移除课件条目(000164 多课件:mid 定位,空 =
// 最新一条;文件/知识库挂接随条目移除,名称登记保留)。
RemoveCourseLibraryMaterial(ctx context.Context, tenantID uint64, id, mid, 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)
+83
View File
@@ -545,6 +545,11 @@ type TrainingCourse struct {
Remark string `json:"remark" gorm:"type:text;default:''"`
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」从课程管理选择后落此关联;可空)。
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
// LibraryPublishStatus 关联课程管理条目的发布状态(联查只读,不落库;
// offline 时学习页/学习入口按「该课程已下线」拦截)。
LibraryPublishStatus string `json:"library_publish_status" gorm:"-"`
// LibraryOffline 关联课程管理条目是否已下线(LibraryPublishStatus 衍生只读)。
LibraryOffline bool `json:"library_offline" gorm:"-"`
// PlanCode 月度计划编号(MP-<YYYYMM>-####,按授课月份分段,创建时由服务端生成,000153)。
PlanCode string `json:"plan_code" gorm:"type:varchar(32);default:''"`
// SourceDemandID 来源需求 id(经理确认自动转月度计划时回填,溯源用,000153)。
@@ -580,6 +585,19 @@ const (
CourseLibraryVerifyConfirmed = "confirmed"
)
// CourseLibraryMaterial 课程管理课件条目(000164,多课件):一次上传/知识库挂接
// 追加一条,不再整体替换;Mid 为条目标识(移除/取流定位用),Name/Size 展示,
// FileKey/KnowledgeID 二选一(视频类仅存原始文件),Origin 标记来源(upload/kb)。
type CourseLibraryMaterial struct {
Mid string `json:"mid"`
Name string `json:"name"`
Size int64 `json:"size"`
FileKey string `json:"file_key"`
KnowledgeID string `json:"knowledge_id"`
Origin string `json:"origin"`
CreatedAt string `json:"created_at"`
}
// TrainingCourseLibrary 课程管理条目(课程资产主数据,000151)。
// 月培训计划的「计划名称」从本表选择,选中计划创建时带 library_course_id 关联。
type TrainingCourseLibrary struct {
@@ -597,7 +615,15 @@ type TrainingCourseLibrary struct {
Description string `json:"description" gorm:"type:text;default:''"`
// SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接
// (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
// 000163 起语义升级为「课程权限」展示文本(部门名+人员名),精确匹配走
// perm_dept_ids/perm_user_ids 两列,本列保留存量兼容与导出展示。
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"`
// PermDeptIDs 课程权限-部门(000163):逗号分隔的 org_depts.id,所选部门整体
// 可见该课程;与 perm_user_ids 同时为空时沿用 suitable_members 存量口径。
PermDeptIDs string `json:"perm_dept_ids" gorm:"type:varchar(512);default:''"`
// PermUserIDs 课程权限-人员(000163):逗号分隔的 users.id,所选人员可见该
// 课程;部门与该部门下人员互斥由前端保证(选了部门无需再选其下人员)。
PermUserIDs string `json:"perm_user_ids" gorm:"type:varchar(1024);default:''"`
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
Category string `json:"category" gorm:"type:varchar(64);default:''"`
// Type 类型(required 必修课/elective 选修课)。
@@ -618,7 +644,11 @@ type TrainingCourseLibrary struct {
// FileSize 课件文件字节数。
FileSize int64 `json:"file_size" gorm:"default:0"`
// KnowledgeID 课件同步知识库「企业培训(课件)」后的文档 id(视频类留空,000153,AI 出题依赖)。
// 000164 起为「最新课件条目」镜像字段(多课件以 Materials 列表为准,主字段
// 恒指向最新一条,发布校验/AI 出题/学习抽屉等既有依赖口径不变)。
KnowledgeID string `json:"knowledge_id" gorm:"type:varchar(36);default:''"`
// Materials 课件列表(000164,多课件;JSON 数组落库):上传/挂接追加不替换。
Materials JSON `json:"materials" gorm:"type:jsonb;default:'[]'"`
// PublishStatus 发布状态(000154):draft 草稿/published 已发布/offline 已下线;
// 培训中心「和信课程」目录仅展示已发布且部门范围覆盖查看人的课程。
PublishStatus string `json:"publish_status" gorm:"type:varchar(16);default:'draft'"`
@@ -649,6 +679,59 @@ type TrainingCourseLibrary struct {
// TableName pins the physical table name.
func (TrainingCourseLibrary) TableName() string { return "tr_course_library" }
// HasPermissionSet 是否已设置课程权限(000163,审核前置):perm 两列任一非空,
// 或存量 suitable_members 非空(含「全部」与自由文本)即视为已设置。
func (m TrainingCourseLibrary) HasPermissionSet() bool {
return strings.TrimSpace(m.PermDeptIDs) != "" ||
strings.TrimSpace(m.PermUserIDs) != "" ||
strings.TrimSpace(m.SuitableMembers) != ""
}
// HasCourseMaterial 是否已有课件(000164:materials 列表任一条,或旧版主字段
// 存量行兜底;名称登记不算,发布/自动发布前置)。
func (m TrainingCourseLibrary) HasCourseMaterial() bool {
return len(m.CourseMaterialList()) > 0 ||
strings.TrimSpace(m.FileKey) != "" ||
strings.TrimSpace(m.KnowledgeID) != ""
}
// CourseMaterialList 解析 materials 列(000164 多课件;空/坏 JSON 返回空列表)。
func (m TrainingCourseLibrary) CourseMaterialList() []CourseLibraryMaterial {
raw := strings.TrimSpace(string(m.Materials))
if raw == "" || raw == "null" || raw == "[]" {
return nil
}
var list []CourseLibraryMaterial
if err := json.Unmarshal(m.Materials, &list); err != nil {
return nil
}
return list
}
// PrimaryCourseMaterial 最新课件条目(主字段镜像对象;列表为空时由旧版主字段
// 构造兜底条目,迁移前的存量行在未跑 000164 回填时仍可展示/下载)。
func (m TrainingCourseLibrary) PrimaryCourseMaterial() *CourseLibraryMaterial {
list := m.CourseMaterialList()
if len(list) > 0 {
return &list[len(list)-1]
}
if m.FileKey == "" && m.KnowledgeID == "" {
return nil
}
origin := "upload"
if m.KnowledgeID != "" && m.FileKey == "" {
origin = "kb"
}
return &CourseLibraryMaterial{
Mid: "primary",
Name: m.FileName,
Size: m.FileSize,
FileKey: m.FileKey,
KnowledgeID: m.KnowledgeID,
Origin: origin,
}
}
// TrainingCourseStudyStats 课程维度的学习/考试参与成员聚合(课程管理列表状态列输入)。
type TrainingCourseStudyStats struct {
// SignedMembers 已签到成员(线下参与)。