feat(training): 需求联动课程管理、适合人员多选、跨空间参与与计划讲师回写(000158-000161)

000158 需求单联动课程管理:
- tr_demands 新增 library_course_id:填报/导入按课程名称在课程管理精准匹配,
  命中自动关联,未命中自动新增待核验课程(000157 流转,发布前须签核完成);
  匹配/建档失败整批回滚并透出原因,不静默跳过
- 需求所属部门强制为填报人本人部门:新建按提报人档案落库(忽略请求值防绕过,
  无部门档案阻断),编辑保留原部门;批量导入按 Excel「部门」列做归属校验
- 编辑时课程名未变保留原课程关联,全量更新不误清

000159 适合人员部门多选:
- tr_course_library.suitable_members 拓宽至 VARCHAR(512):存「、」分隔多部门名
  或「全部」,存量单值/自由文本兼容(分隔符匹配时归一)
- 课程管理/需求表单改多选交互,「全部」与具体部门互斥

000160 企业培训跨空间参与:
- 培训域数据空间按员工档案归属解析(当前空间有培训档案优先,否则回落最早
  在职档案所在空间),路由组 TrainingTenantResolution 中间件统一注入
- 中间件同步回落请求上下文执行租户:课件文件流(GetKnowledgeFile)、培训
  知识库 ensure 等 ctx 租户链路落在档案空间;caller 身份保持当前工作区,
  授权口径不变(修复跨空间学员课件预览 403「Permission denied」与文件流 404)
- 课程学习详情页课件预览统一走培训域文件流(/training/materials/:id/file),
  不再请求知识库守卫路由(/knowledge/:id/preview);附空间解析中间件单元测试
- 培训中心「和信课程」目录(scope=catalog):已发布 + 适合人员覆盖即可见;
  卡片点开即学(课件在线预览抽屉 + 下载);计划无材料行时以课程管理条目
  合成课件回退取流
- /training/members/me 联查返回部门名,支撑适合人员匹配与表单默认值

000161 计划讲师回写与发布校验:
- 月培训计划讲师计划侧可改,改动回写课程管理主数据并重置待核验(发布前须
  重新签核),同步补讲师 lecturer 角色绑定
- 发布必填校验:关联课程管理且已签核、参加人员;线下计划另需授课时间/地点/
  讲师(线上计划豁免);跨场次名单去重成员数校验
This commit is contained in:
runny committed 2026-11-24 10:03:58 +08:00
1 parent 3c8b595064
commit 0819f8c4d1
24 files changed
+1084 -202

No files matched your search

@@ -48,6 +48,25 @@ func (r *trainingRepository) GetMemberByUserID(ctx context.Context, tenantID uin
return &m, nil
}
// FindArchiveTenantID 跨租户查找用户最早的在职员工档案所属租户(000160):
// 企业培训按「员工档案归属」解析数据空间 —— 用户当前所在工作区没有培训档案、
// 但组织中心(共享 org_employees)有在职档案时,培训域回落到档案所在租户,
// 同一组织的人员不因所在工作区不同而看不到企业培训。无档案返回 0,nil。
func (r *trainingRepository) FindArchiveTenantID(ctx context.Context, userID string) (uint64, error) {
var tenantIDs []uint64
err := r.db.WithContext(ctx).Model(&types.OrgEmployee{}).
Where("user_id = ? AND status = ?", userID, "active").
Order("created_at ASC").Limit(1).
Pluck("tenant_id", &tenantIDs).Error
if err != nil {
return 0, err
}
if len(tenantIDs) == 0 {
return 0, nil
}
return tenantIDs[0], nil
}
// ---------------------------------------------------------------------------
// 学习/积分/规则/通知
// ---------------------------------------------------------------------------
@@ -31,6 +31,21 @@ 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 多部门口径:值按「、」拆分(逗号/分号
// 兼容归一)后与调用方部门名做成员匹配;未设置适合人员的存量课程沿用
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。调用方
// 无部门档案时只见「全部」与未设置的课程。
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,
)
}
}
var total int64
if err := tx.Count(&total).Error; err != nil {
@@ -59,6 +74,19 @@ func (r *trainingRepository) ListCourseLibrary(ctx context.Context, tenantID uin
return items, total, err
}
// FindCourseLibraryByName fetches one course-library item by exact course name
// (需求侧课程自动匹配,000158:按课程名称精准查找,同名存量取最早一条)。
func (r *trainingRepository) FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error) {
var item types.TrainingCourseLibrary
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND name = ?", tenantID, name).
Order("created_at ASC").
First(&item).Error; err != nil {
return nil, err
}
return &item, nil
}
// GetCourseLibraryItem fetches one course-library item.
func (r *trainingRepository) GetCourseLibraryItem(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseLibrary, error) {
var item types.TrainingCourseLibrary
@@ -119,6 +119,7 @@ func (r *trainingRepository) UpdateDemand(ctx context.Context, demand *types.Tra
"lecturer_id": demand.LecturerID,
"lecturer_external": demand.LecturerExternal,
"course_name": demand.CourseName,
"library_course_id": demand.LibraryCourseID,
"plant": demand.Plant,
"category": demand.Category,
"session_count": demand.SessionCount,
@@ -527,6 +528,18 @@ func (r *trainingRepository) CountEnrolledMembersByCourse(ctx context.Context, t
return out, nil
}
// CountEnrolledMembersByCourseID 单课程的场次学员名单人数(发布必填校验用,
// 000161:跨场次名单去重成员数;与 CountEnrolledMembersByCourse 同口径)。
func (r *trainingRepository) CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error) {
var cnt int64
err := r.db.WithContext(ctx).
Table("tr_enrollments e").
Joins("JOIN tr_course_sessions s ON s.id = e.session_id AND s.tenant_id = e.tenant_id AND s.deleted_at IS NULL").
Where("e.tenant_id = ? AND s.course_id = ?", tenantID, courseID).
Count(&cnt).Error
return int(cnt), err
}
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(去重成员集合):
// 签到走场次联查;学习任务直接带课程;考试支持场次卷与线上自学卷
// (session 为空时经 paper→bank→course 兜底)两条路径。
+94 -4
View File
@@ -291,6 +291,25 @@ func (s *trainingService) CurrentMember(ctx context.Context, tenantID uint64, us
}, nil
}
// ResolveTrainingTenant 企业培训数据空间解析(000160):培训域不再绑定单一工作区
// —— 同一组织的人员只要员工档案(org_employees)里存在,无论当前在哪个工作区,
// 都按其档案所在空间参与培训、课程发布与学习。优先级:
// 1. 当前空间已有培训档案 → 当前空间(多档案用户显式切换工作区的语义优先);
// 2. 否则跨空间取最早在职档案所在空间;
// 3. 都没有 → 维持当前空间(默认学员口径,行为与升级前一致)。
func (s *trainingService) ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error) {
if userID == "" || activeTenantID == 0 {
return activeTenantID, nil
}
if _, err := s.repo.GetMemberByUserID(ctx, activeTenantID, userID); err == nil {
return activeTenantID, nil
}
if tenantID, err := s.repo.FindArchiveTenantID(ctx, userID); err == nil && tenantID != 0 {
return tenantID, nil
}
return activeTenantID, nil
}
// trainingMemberWithRoles 填充员工档案的培训模块绑定角色展示字段。
func (s *trainingService) trainingMemberWithRoles(ctx context.Context, tenantID uint64, member *types.TrainingMember) (*types.TrainingMember, error) {
binding, err := s.org.GetModuleMember(ctx, tenantID, types.OrgModuleTraining, member.ID)
@@ -372,6 +391,8 @@ func (s *trainingService) EnsureLecturerRole(ctx context.Context, tenantID uint6
// SaveDemand creates or updates one demand with rule-based field checking.
// 已确认的需求不再允许编辑(先由人事回退)。
func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, demand *types.TrainingDemand) (*types.TrainingDemand, error) {
// 编辑场景的存量值(课程关联保留口径,见下方课程校验)。
var prevLibraryCourseID, prevCourseName string
if demand.CourseName == "" {
return nil, errors.NewBadRequestError("课程名称不能为空")
}
@@ -393,6 +414,10 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
if existing.Status == types.TrainingDemandConfirmed {
return nil, errors.NewBadRequestError("已确认的需求不可编辑")
}
// 编辑保留原课程关联(000158):课程名未变时跳过重匹配,匹配失败时不
// 清空已有关联(UpdateDemand 全量更新,零值会误清)。
prevLibraryCourseID = existing.LibraryCourseID
prevCourseName = existing.CourseName
}
// 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
@@ -413,6 +438,33 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
demand.Status = types.TrainingDemandSubmitted
}
// 课程校验(000158):按课程名称在课程管理精准查找,命中自动匹配该课程;
// 未命中自动新增该课程(待核验,归属需求部门)。匹配/建档失败为硬失败:
// 整个保存随之中止并向前端透出原因(不静默跳过,避免"需求存了但课程没建"
// 的隐性不一致)。课程名未变且已有关联时跳过重匹配(编辑保留原关联)。
// 外部讲师口径已在上方互斥清空,这里原样透传即可。
switch {
case prevLibraryCourseID != "" && prevCourseName == demand.CourseName:
demand.LibraryCourseID = prevLibraryCourseID
case strings.TrimSpace(demand.CourseName) != "":
proto := &types.TrainingCourseLibrary{
Name: demand.CourseName,
OwnerDeptID: demand.DeptID,
Category: demand.Category,
SuitableMembers: demand.PostScope,
LecturerID: demand.LecturerID,
LecturerExternal: demand.LecturerExternal,
}
id, _, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, demand.SubmitterID)
if err != nil {
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, demand.CourseName, err)
return nil, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
}
demand.LibraryCourseID = id
default:
demand.LibraryCourseID = prevLibraryCourseID
}
if demand.ID == "" {
demand.ID = trainingNewID()
demand.TenantID = tenantID
@@ -431,10 +483,14 @@ func (s *trainingService) SaveDemand(ctx context.Context, tenantID uint64, deman
}
// ImportDemands batch-imports demands (调研表在线化/邮件替代)。
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error) {
// 返回导入行与自动新增的待核验课程数(000158)。
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error) {
if len(demands) == 0 {
return nil, errors.NewBadRequestError("导入数据为空")
return nil, 0, errors.NewBadRequestError("导入数据为空")
}
// 课程校验批内去重(000158):同名行只查/建一次,其余行复用条目 id。
courseCache := map[string]string{}
coursesCreated := 0
for i := range demands {
demands[i].ID = trainingNewID()
demands[i].TenantID = tenantID
@@ -450,17 +506,51 @@ func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, de
// 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
// 讲师口径互斥与 SaveDemand 一致:系统员工优先,外部姓名仅在无 id 时生效。
if demands[i].LecturerID != "" {
demands[i].LecturerExternal = ""
}
msgs := []string{}
if demands[i].DeptID == "" {
msgs = append(msgs, "未指定部门")
}
demands[i].CheckMsg = strings.Join(msgs, ";")
demands[i].CheckStatus = types.TrainingCheckPending
// 课程校验(000158):按名称精准查找自动匹配,未命中自动新增(待核验)。
// 硬失败同 SaveDemand:任一行匹配/建档失败整批中止并透出原因;
// 批内同名复用首个条目,不重复建档。
name := strings.TrimSpace(demands[i].CourseName)
if name == "" {
continue
}
if id, ok := courseCache[name]; ok {
demands[i].LibraryCourseID = id
continue
}
proto := &types.TrainingCourseLibrary{
Name: name,
OwnerDeptID: demands[i].DeptID,
Category: demands[i].Category,
SuitableMembers: demands[i].PostScope,
LecturerID: demands[i].LecturerID,
LecturerExternal: demands[i].LecturerExternal,
}
id, created, err := s.matchOrCreateLibraryCourse(ctx, tenantID, proto, updaterID)
if err != nil {
logger.Warnf(ctx, "[Training] demand course match/create failed, tenant=%d course=%s error: %v", tenantID, name, err)
return nil, 0, errors.NewInternalServerError("课程自动匹配/新增失败,请稍后重试").WithDetails(err.Error())
}
courseCache[name] = id
demands[i].LibraryCourseID = id
if created {
coursesCreated++
}
}
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
return nil, err
return nil, 0, err
}
return demands, nil
return demands, coursesCreated, nil
}
// ConfirmDemand marks one demand confirmed and auto-aggregates it into the
+121 -15
View File
@@ -130,9 +130,10 @@ func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id str
}
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
// 课程名称/类型/形式/讲师随课程管理主数据,计划侧不支持修改;新建时学时/课程编号/
// 适用部门(主办单位)/参加人员预填。课程管理条目缺失时按原值保存(fail-open)。
// 返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
// 课程名称/类型/形式随课程管理主数据锁定;讲师 000161 起计划侧可改(更新路径
// 不再覆盖,改动经 syncPlanLecturerToLibrary 回写主数据并重置待核验);新建时
// 讲师/学时/课程编号/适用部门(主办单位)/参加人员预填。课程管理条目缺失时按
// 原值保存(fail-open)。返回命中的课程管理条目(无关联返回 nil),供调用方继续带出课件等资料。
func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantID uint64, course *types.TrainingCourse, isCreate bool) *types.TrainingCourseLibrary {
if course.LibraryCourseID == "" {
return nil
@@ -146,7 +147,8 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
course.Name = item.Name
course.Type = item.Type
course.Mode = item.Mode
if item.LecturerID != "" || item.LecturerExternal != "" {
if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") {
// 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。
course.LecturerID = item.LecturerID
course.LecturerExternal = item.LecturerExternal
}
@@ -172,6 +174,35 @@ func (s *trainingService) applyLibraryCourseBinding(ctx context.Context, tenantI
return item
}
// syncPlanLecturerToLibrary 计划侧讲师改动回写课程管理主数据(000161):
// 讲师(系统员工 id/外部姓名)与课程管理条目不一致时经 SaveCourseLibraryItem
// 回写——其编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须由
// 所属部门课长/经理重新签核。fail-open:回写失败记日志不阻断计划保存。
func (s *trainingService) syncPlanLecturerToLibrary(ctx context.Context, tenantID uint64, item *types.TrainingCourseLibrary, course *types.TrainingCourse, updaterID string) {
if item == nil || course == nil {
return
}
lecturerID, lecturerExt := strings.TrimSpace(course.LecturerID), strings.TrimSpace(course.LecturerExternal)
if lecturerID != "" {
lecturerExt = ""
}
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
return
}
updated := *item
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
if _, err := s.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync plan lecturer to course library", err, "library_course_id", item.ID)
return
}
logger.Infof(ctx, "[Training] plan lecturer synced to library (verify reset), tenant=%d course=%s operator=%s", tenantID, item.Code, updaterID)
// 讲师自动补齐 lecturer 角色绑定(讲师名册/下拉可见,fail-open)。
if err := s.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role on plan sync", err)
}
}
// attachLibraryCourseMaterial 课程管理课件的计划侧挂接(000153,新建计划时):
// 课程管理条目已维护课件(知识库文档/原始文件/名称登记)时自动创建一条课程课件
// 记录,学员学习页与线上发布校验(线上课必须有课件)沿用既有链路。fail-open。
@@ -232,8 +263,8 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
return course, nil
}
course.TenantID = tenantID
// 课程管理关联存在时锁定带出字段(000153;更新侧同样生效,防止前端篡改)。
s.applyLibraryCourseBinding(ctx, tenantID, course, false)
// 课程管理关联存在时锁定带出字段(000153;讲师 000161 起计划侧可改)。
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, false)
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
if err != nil {
@@ -242,6 +273,10 @@ func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, cours
if err := s.repo.UpdateCourse(ctx, course); err != nil {
return nil, err
}
// 计划侧讲师改动回写课程管理并重置待核验(000161):发布前须重新签核。
if old == nil || old.LecturerID != course.LecturerID || old.LecturerExternal != course.LecturerExternal {
s.syncPlanLecturerToLibrary(ctx, tenantID, libItem, course, updaterID)
}
if old != nil {
s.recordCourseChangeLog(ctx, tenantID, course.ID, old, course, updaterID)
}
@@ -358,15 +393,54 @@ func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id
if course.Status == types.TrainingCoursePublished {
return course, nil
}
// 关联课程管理条目须已核验确认(000157):月培训计划发布/保存并发布共用本端点,
// 未核验的课程拦截并友好提示,核验入口在「课程管理」。
if course.LibraryCourseID != "" {
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if libErr != nil || lib == nil {
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程")
// 发布必填校验(000161):课程(须关联课程管理且已签核)、参加人员;
// 线下计划另需授课时间/授课地点/讲师(线上计划豁免这三项)。
if strings.TrimSpace(course.LibraryCourseID) == "" {
return nil, errors.NewBadRequestError("发布前需先关联课程管理课程")
}
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if libErr != nil || lib == nil {
return nil, errors.NewBadRequestError("关联的课程管理条目不存在,请先在「课程管理」中确认该课程")
}
// 课程须已完成签核(000157/000158):未核验(待核验)时按统一文案拦截,核验入口在「课程管理」。
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed {
return nil, errors.NewBadRequestError("请联系课长或经理审核课程!").
WithDetails(fmt.Sprintf("课程《%s》尚未完成签核,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name))
}
// 线上计划课件校验(原 handler 前置,收口到 service 统一口径):计划自带课件
// 或关联课程的课程管理课件(名称登记/文件/知识库文档,000156 随课程带出)
// 任一有值即可;考题非必填,不参与发布校验。
if course.Mode == types.TrainingCourseModeOnline {
materials, matErr := s.repo.ListMaterials(ctx, tenantID, course.ID)
if matErr != nil {
return nil, matErr
}
if lib.VerifyStatus != types.CourseLibraryVerifyConfirmed {
return nil, errors.NewBadRequestError(fmt.Sprintf("关联课程《%s》尚未核验确认,请先在「课程管理」中由所属部门课长/经理核验后再发布", lib.Name))
hasLibCourseware := strings.TrimSpace(lib.MaterialName) != "" ||
strings.TrimSpace(lib.FileKey) != "" ||
strings.TrimSpace(lib.KnowledgeID) != ""
if len(materials) == 0 && !hasLibCourseware {
return nil, errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)")
}
}
// 参加人员:适用人员非空或场次学员名单有人(跨场次)任一满足即可。
if strings.TrimSpace(course.PostScope) == "" {
enrolled, enrolledErr := s.repo.CountEnrolledMembersByCourseID(ctx, tenantID, course.ID)
if enrolledErr != nil {
return nil, enrolledErr
}
if enrolled == 0 {
return nil, errors.NewBadRequestError("发布前需先设置参加人员")
}
}
if course.Mode != types.TrainingCourseModeOnline {
if strings.TrimSpace(course.TeachTime) == "" {
return nil, errors.NewBadRequestError("发布前需先设置授课时间")
}
if strings.TrimSpace(course.Location) == "" {
return nil, errors.NewBadRequestError("发布前需先设置授课地点")
}
if strings.TrimSpace(course.LecturerID) == "" && strings.TrimSpace(course.LecturerExternal) == "" {
return nil, errors.NewBadRequestError("发布前需先指定讲师")
}
}
course.Status = types.TrainingCoursePublished
@@ -578,8 +652,40 @@ func (s *trainingService) CreateMaterial(ctx context.Context, tenantID uint64, m
}
// ListMaterials returns course materials.
// 计划未自带课件时回退关联课程的课程管理课件(000156 随课程带出,发布校验同口径):
// 以课程管理条目 id 作为虚拟课件 id 返回,学习详情页预览/文件流/进度上报同链路可用
// (GetMaterialFile 对虚拟 id 回退课程管理文件流);仅登记名称而无文件/知识库文档时
// 不合成(无内容可打开)。
func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) {
return s.repo.ListMaterials(ctx, tenantID, courseID)
items, err := s.repo.ListMaterials(ctx, tenantID, courseID)
if err != nil || len(items) > 0 || courseID == "" {
return items, err
}
course, cErr := s.repo.GetCourse(ctx, tenantID, courseID)
if cErr != nil || course == nil || strings.TrimSpace(course.LibraryCourseID) == "" {
return items, nil
}
lib, libErr := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if libErr != nil || lib == nil || (lib.KnowledgeID == "" && lib.FileKey == "") {
return items, nil
}
name := strings.TrimSpace(lib.FileName)
if name == "" {
name = strings.TrimSpace(lib.MaterialName)
}
if name == "" {
name = lib.Name
}
return []*types.TrainingMaterial{{
ID: lib.ID,
TenantID: tenantID,
CourseID: courseID,
Kind: "doc",
Name: name,
FileKey: lib.FileKey,
KnowledgeID: lib.KnowledgeID,
Size: lib.FileSize,
}}, nil
}
// AttachQuestionBank 建课/编辑课时反向关联题库:把 bank.course_id 指向课程,
@@ -221,6 +221,11 @@ func trainingKBSummary(kb *types.KnowledgeBase) *types.TrainingKnowledgeBaseSumm
func (s *trainingService) GetMaterialFile(ctx context.Context, tenantID uint64, materialID string) (io.ReadCloser, string, error) {
material, err := s.repo.GetMaterial(ctx, tenantID, materialID)
if err != nil {
// 虚拟课件回退(ListMaterials 计划无课件时以课程管理条目 id 合成课件):
// 材料行不存在时按课程管理条目取文件流,与发布/学习链路同口径。
if rc, fileName, libErr := s.GetCourseLibraryMaterialFile(ctx, tenantID, materialID); libErr == nil {
return rc, fileName, nil
}
return nil, "", werrors.NewNotFoundError("课件不存在")
}
if material.KnowledgeID != "" {
@@ -2,6 +2,7 @@ package service
import (
"context"
"errors"
"fmt"
"io"
"mime/multipart"
@@ -9,6 +10,7 @@ import (
"time"
excelize "github.com/xuri/excelize/v2"
"gorm.io/gorm"
werrors "academy/internal/errors"
"academy/internal/logger"
@@ -107,6 +109,11 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
item.VerifyStatus = types.CourseLibraryVerifyPending
// 仅传部门名时按组织架构解析为 id(不阻断保存)。
s.resolveCourseLibraryDept(ctx, tenantID, item)
// 所属部门强制为创建人部门(000160):前端表单同口径锁定,服务端兜底
// 覆盖,防止绕过前端改部门。创建人无部门档案时保留原值(可为空)。
if member, err := s.CurrentMember(ctx, tenantID, updaterID); err == nil && member != nil && member.DeptID != "" {
item.OwnerDeptID = member.DeptID
}
// 课程编号(CRS-####,创建时由服务端生成;编号列只读,不收前端值)。
item.Code = s.nextCourseLibraryCode(ctx, tenantID)
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
@@ -131,6 +138,8 @@ func (s *trainingService) SaveCourseLibraryItem(ctx context.Context, tenantID ui
if item.KnowledgeID == "" {
item.KnowledgeID = old.KnowledgeID
}
// 所属部门不可随编辑修改(000160):恒保持创建时的部门,前端表单同口径锁定。
item.OwnerDeptID = old.OwnerDeptID
// 编辑即回待核验(000157):内容变更后原核验结论作废,需重新核验。
item.VerifyStatus = types.CourseLibraryVerifyPending
item.ConfirmedBy = ""
@@ -215,6 +224,51 @@ func (s *trainingService) VerifyCourseLibraryItems(ctx context.Context, tenantID
return verified, skipped, nil
}
// matchOrCreateLibraryCourse 需求侧课程校验(000158):按课程名称在课程管理精准
// 查找,命中直接复用(自动匹配该课程);未命中自动新增该课程——待核验(000157
// 流转)、草稿、归属需求部门,由所属部门课长/经理核验,发布前必须已签核完成。
// proto 携带需求行带入的名称/部门/讲师/分类/适合人员,其余字段按课程管理默认口径。
// 返回条目 id 与是否新建。查询/建档失败一律返回错误(硬失败,不静默跳过),
// 由需求保存/导入整批回滚并向前端透出真实原因。
func (s *trainingService) matchOrCreateLibraryCourse(ctx context.Context, tenantID uint64, proto *types.TrainingCourseLibrary, creatorID string) (string, bool, error) {
name := strings.TrimSpace(proto.Name)
if name == "" {
return "", false, werrors.NewBadRequestError("课程名称不能为空")
}
hit, err := s.repo.FindCourseLibraryByName(ctx, tenantID, name)
switch {
case err == nil && hit != nil:
return hit.ID, false, nil
case !errors.Is(err, gorm.ErrRecordNotFound):
// 查询本身出错(非未命中):不得当作"不存在"去重复建档,直接上抛。
return "", false, err
}
item := &types.TrainingCourseLibrary{
ID: trainingNewID(),
TenantID: tenantID,
Name: name,
Code: s.nextCourseLibraryCode(ctx, tenantID),
OwnerDeptID: proto.OwnerDeptID,
Category: strings.TrimSpace(proto.Category),
SuitableMembers: strings.TrimSpace(proto.SuitableMembers),
LecturerID: proto.LecturerID,
LecturerExternal: strings.TrimSpace(proto.LecturerExternal),
Type: "required",
Mode: types.TrainingCourseModeOffline,
PublishStatus: "draft",
VerifyStatus: types.CourseLibraryVerifyPending,
CreatorID: creatorID,
}
if item.LecturerID != "" {
item.LecturerExternal = ""
}
if err := s.repo.CreateCourseLibraryItem(ctx, item); err != nil {
return "", false, err
}
logger.Infof(ctx, "[Training] demand course auto-created to library, tenant=%d course=%s dept=%s creator=%s", tenantID, item.Code, item.OwnerDeptID, creatorID)
return item.ID, true, nil
}
// ImportCourseLibraryItems 批量导入(前端解析 Excel 后逐行提交,讲师已在
// 前端按员工名册解析为 id / 外部姓名,与需求导入同口径)。
func (s *trainingService) ImportCourseLibraryItems(ctx context.Context, tenantID uint64, items []*types.TrainingCourseLibrary, updaterID string) (int, error) {