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) {
+174 -50
View File
@@ -32,12 +32,41 @@ func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotifi
return &Handler{svc: svc, pusher: pusher}
}
// trainingTenantContextKey 培训域解析后的数据空间租户 id(000160):由
// TrainingTenantResolution 中间件写入,callerTenantID 优先读取。
const trainingTenantContextKey = "training_tenant_id"
// TrainingTenantResolution 企业培训数据空间解析中间件(000160):认证守卫之后
// 执行,按「当前空间有培训档案优先,否则回退员工档案所在空间」解析培训域实际
// 读写的租户并写入上下文;本组所有 handler 的 callerTenantID 均取解析值 ——
// 同一组织的人员切换到任意工作区,都能看到并参与其档案所属组织的企业培训。
func (h *Handler) TrainingTenantResolution() gin.HandlerFunc {
return func(c *gin.Context) {
active := c.GetUint64(types.TenantIDContextKey.String())
userID := callerUserID(c)
if active != 0 && userID != "" {
if resolved, err := h.svc.ResolveTrainingTenant(c.Request.Context(), active, userID); err == nil && resolved != 0 {
c.Set(trainingTenantContextKey, resolved)
// 执行租户随培训空间同步回落(000160):课件文件流(GetKnowledgeFile)、
// 培训知识库 ensure 等按 ctx 租户读写的服务链路才落在档案所在空间;
// caller 身份保持当前工作区不变,授权口径不受影响。
c.Request = c.Request.WithContext(types.WithExecutionTenant(c.Request.Context(), resolved))
}
}
c.Next()
}
}
// ---------------------------------------------------------------------------
// 请求上下文辅助
// ---------------------------------------------------------------------------
// callerTenantID reads the tenant id injected by the auth middleware.
// callerTenantID reads the tenant id injected by the auth middleware, or the
// training-resolved tenant (000160) when the route group middleware resolved one.
func callerTenantID(c *gin.Context) uint64 {
if v := c.GetUint64(trainingTenantContextKey); v != 0 {
return v
}
return c.GetUint64(types.TenantIDContextKey.String())
}
@@ -400,6 +429,18 @@ func (h *Handler) Me(c *gin.Context) {
_ = c.Error(err)
return
}
// 联查部门名(000160):员工档案只存 dept_id,前端课程目录按部门名匹配
// 「适合人员」、表单默认值展示均需要名称;档案无部门时保持空串。
if member.DeptID != "" {
if depts, err := h.svc.ListDepts(ctx, callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == member.DeptID {
member.DeptName = d.Name
break
}
}
}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
}
@@ -436,9 +477,12 @@ func (h *Handler) ListDemandYears(c *gin.Context) {
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
type saveDemandRequest struct {
ID string `json:"id"`
Year int `json:"year"`
DeptID string `json:"dept_id"`
ID string `json:"id"`
Year int `json:"year"`
DeptID string `json:"dept_id"`
// DeptName Excel「部门」列原始值(仅批量导入部门归属校验用,000158:全部行
// 必须为导入人本人部门;在线提报不传,服务端强制按提报人部门落库)。
DeptName string `json:"dept_name"`
CourseName string `json:"course_name" binding:"required"`
Plant string `json:"plant"`
Category string `json:"category"`
@@ -504,14 +548,23 @@ func (h *Handler) SaveDemand(c *gin.Context) {
return
}
}
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。
deptID := trimSpace(req.DeptID)
if deptID == "" {
if existing != nil {
deptID = existing.DeptID
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil {
deptID = member.DeptID
// 部门口径(000158):所属部门必须为填报人本人部门——新建强制按提报人所在
// 部门(org_employees.dept_id)落库,忽略请求值防绕过;编辑保留原部门(人事
// 代改也不覆盖归属)。提报人无部门档案时阻断,先由人事在组织中心维护。
var deptID string
if existing != nil {
deptID = existing.DeptID
} else {
member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再提报"))
return
}
deptID = member.DeptID
}
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
ID: req.ID, Year: req.Year, DeptID: deptID,
@@ -575,6 +628,9 @@ func (h *Handler) ListPosts(c *gin.Context) {
}
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。
// 部门口径(000158):全部行必须为导入人本人部门(org_employees.dept_id,全员
// 严格,人事也不例外);部门列留空视为默认导入人部门,其余任一行不符即整批
// 拒绝。导入人无部门档案时阻断,先由人事在组织中心维护。
func (h *Handler) ImportDemands(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
@@ -587,10 +643,47 @@ func (h *Handler) ImportDemands(c *gin.Context) {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
tenantID, userID := callerTenantID(c), callerUserID(c)
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
if err != nil {
_ = c.Error(err)
return
}
if member == nil || trimSpace(member.DeptID) == "" {
_ = c.Error(errors.NewBadRequestError("未找到您的部门档案,请联系人事在组织中心维护部门后再导入"))
return
}
// 整批部门预检:任一行部门与导入人不符即拒绝,不做部分导入。
// 通过口径:行部门 id 与本人一致,或部门列全空(默认导入人部门)。
myDeptName := h.deptNameOf(ctx, tenantID, member.DeptID)
violations := make([]string, 0, len(req.Demands))
for i, item := range req.Demands {
deptID, deptName := trimSpace(item.DeptID), trimSpace(item.DeptName)
if deptID == "" && deptName == "" {
continue
}
if deptID == member.DeptID {
continue
}
if deptName == "" {
deptName = h.deptNameOf(ctx, tenantID, deptID)
}
if deptName == "" {
deptName = deptID
}
violations = append(violations, fmt.Sprintf("第%d行(%s)", i+1, deptName))
}
if len(violations) > 0 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf(
"导入失败:第%s行部门与您所在部门(%s)不一致,仅可导入本人部门的需求表",
strings.Join(violations, "、"), myDeptName)))
return
}
demands := make([]*types.TrainingDemand, 0, len(req.Demands))
for _, item := range req.Demands {
demands = append(demands, &types.TrainingDemand{
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName,
// 部门强制为导入人本人部门:部门列留空的行在此默认,其余已通过预检。
Year: item.Year, DeptID: member.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),
@@ -598,16 +691,34 @@ func (h *Handler) ImportDemands(c *gin.Context) {
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
})
}
result, err := h.svc.ImportDemands(ctx, callerTenantID(c), demands, callerUserID(c))
result, coursesCreated, err := h.svc.ImportDemands(ctx, tenantID, demands, userID)
if err != nil {
_ = c.Error(err)
return
}
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
h.syncDemandLecturerToLibrary(ctx, tenantID, userID, 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}})
notified := h.notifyDemandVerify(ctx, tenantID, demands)
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"imported": len(result), "notified": notified, "courses_created": coursesCreated}})
}
// deptNameOf 部门 id → 名称(导入报错文案用;查不到时回退展示 id)。
func (h *Handler) deptNameOf(ctx context.Context, tenantID uint64, deptID string) string {
if trimSpace(deptID) == "" {
return ""
}
depts, err := h.svc.ListDepts(ctx, tenantID)
if err != nil {
return deptID
}
for _, d := range depts {
if d != nil && d.ID == deptID {
return d.Name
}
}
return deptID
}
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
@@ -681,10 +792,13 @@ func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand
PostScope: demand.PostScope,
}
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
// 课程管理关联(000158):需求填报/导入时已按名称精准匹配并回填
// library_course_id(未命中自动新增待核验课程),此处直接采用;存量需求
// 无值时回退课程管理同名扫描兜底(计划侧自动带出并锁定课程信息)。
course.SourceDemandID = demand.ID
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
if trimSpace(demand.LibraryCourseID) != "" {
course.LibraryCourseID = demand.LibraryCourseID
} else 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
@@ -901,47 +1015,75 @@ func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, op
}
}
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
// syncDemandLecturerToLibrary 需求课程信息回写课程管理(000156/000161):需求
// (导入/在线保存/编辑)所关联的课程管理条目——优先 demand.library_course_id
// (000158 自动匹配),无值回退同名匹配——讲师与条目不一致时以需求为准更新;
// 000161 扩展:分类/适合人员(需求侧改后)同样回写。SaveCourseLibraryItem 的
// 编辑副作用即重置该课程为待核验并清空核验人/时间,发布前须重新签核。
// 同批同名取首条。fail-open:失败仅记日志不阻断保存/导入。
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
byID := map[string]*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) == "" {
if id := trimSpace(d.LibraryCourseID); id != "" {
if _, ok := byID[id]; !ok {
byID[id] = d
}
continue
}
if _, ok := byName[d.CourseName]; !ok {
byName[d.CourseName] = d
}
}
if len(byName) == 0 {
if len(byID) == 0 && 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)
logger.Error(ctx, "Failed to list course library for demand sync", err)
return
}
for _, item := range items {
if item == nil {
continue
}
d, ok := byName[item.Name]
d, ok := byID[item.ID]
if !ok {
d, ok = byName[item.Name]
}
if !ok {
continue
}
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
if lecturerID != "" {
lecturerExt = ""
}
hasLecturer := lecturerID != "" || lecturerExt != ""
category, suitable := trimSpace(d.Category), trimSpace(d.PostScope)
// 仅按需求侧非空字段判断差异(空值=未填,不覆盖课程管理已有值,防止
// 旧行误清讲师/分类);任一非空字段与条目不一致才回写并重置待核验。
changed := (hasLecturer && (item.LecturerID != lecturerID || item.LecturerExternal != lecturerExt)) ||
(category != "" && item.Category != category) ||
(suitable != "" && item.SuitableMembers != suitable)
if !changed {
continue
}
updated := *item
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
if hasLecturer {
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
}
if category != "" {
updated.Category = category
}
if suitable != "" {
updated.SuitableMembers = suitable
}
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync demand lecturer to course library", err)
logger.Error(ctx, "Failed to sync demand course info to course library", err)
continue
}
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
@@ -1221,26 +1363,8 @@ func (h *Handler) PublishCourse(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。
course, err := h.svc.GetCourse(ctx, callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if course.Mode == "online" {
materials, err := h.svc.ListMaterials(ctx, callerTenantID(c), course.ID)
if err != nil {
_ = c.Error(err)
return
}
if len(materials) == 0 {
_ = c.Error(errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)"))
return
}
} else if trimSpace(course.LecturerID) == "" {
_ = c.Error(errors.NewBadRequestError("线下课程发布前需先指定讲师"))
return
}
// 发布前置校验(线上课件/线下讲师等)统一收口在 service PublishCourse:
// 线上课件认计划自带或课程管理自带课件,考题非必填。
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
if err != nil {
_ = c.Error(err)
+23 -1
View File
@@ -66,9 +66,31 @@ func toCourseLibrary(req saveCourseLibraryRequest) *types.TrainingCourseLibrary
// ListCourseLibrary GET /training/course-library — 课程管理列表(关键字分页)。
// 数据范围按调用方角色强制注入(000157):人事全部/课长经理本部门/讲师学员仅
// 「与我相关」;月培训计划「计划名称」下拉同源,口径一致。
// scope=catalog(000160)为学员目录口径:已发布 + 适合人员覆盖调用方
// (「全部」或调用方部门名;未设置适合人员沿用原部门范围口径),不按维护
// 角色收窄 —— 目录面向全体员工,「培训中心·和信课程」同源。
func (h *Handler) ListCourseLibrary(c *gin.Context) {
q := listQueryFromRequest(c)
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
if q.Scope == "catalog" {
q.CatalogOnly = true
// 调用方部门(id+名)用于适合人员匹配;无培训档案的调用方两个字段
// 留空(仅见「全部」与未设置适合人员的课程),不阻断目录查询。
if member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c)); err == nil && member != nil {
q.CatalogDeptID = member.DeptID
}
if q.CatalogDeptID != "" {
if depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c)); err == nil {
for _, d := range depts {
if d.ID == q.CatalogDeptID {
q.CatalogDeptName = d.Name
break
}
}
}
}
} else {
q.DeptID, q.RelatedUserID = h.callerCourseLibraryScope(c)
}
items, total, err := h.svc.ListCourseLibraryItems(c.Request.Context(), callerTenantID(c), q)
if err != nil {
_ = c.Error(err)
@@ -0,0 +1,90 @@
package training
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubTenantResolution 只覆盖空间解析;被测中间件不触碰其余服务面。
type stubTenantResolution struct {
interfaces.TrainingService
resolved uint64
}
func (s *stubTenantResolution) ResolveTrainingTenant(_ context.Context, _ uint64, _ string) (uint64, error) {
return s.resolved, nil
}
// seedAuthSession 模拟认证中间件 applyAuthSession 的双面写入(gin keys + 请求
// 上下文,含 Caller),保证被测中间件读到与线上一致的请求状态。
func seedAuthSession(c *gin.Context, tenantID uint64, userID string) {
req := httptest.NewRequest(http.MethodGet, "/api/v1/training/courses", nil)
ctx := types.WithCaller(req.Context(), types.Caller{TenantID: tenantID, UserID: userID, Role: types.TenantRoleViewer})
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
ctx = context.WithValue(ctx, types.UserIDContextKey, userID)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
c.Request = req.WithContext(ctx)
c.Set(types.TenantIDContextKey.String(), tenantID)
c.Set(types.UserIDContextKey.String(), userID)
}
// TestTrainingTenantResolutionRewritesExecutionTenant 000160 跨空间学员:当前
// 空间无培训档案时,执行租户必须随培训空间回落(课件文件流 GetKnowledgeFile、
// 培训知识库 ensure 等按 ctx 租户读写的链路落在档案所在空间),caller 身份保持
// 当前工作区不变 —— 否则知识库文档按当前空间检索会 404,跨空间鉴权被 403。
func TestTrainingTenantResolutionRewritesExecutionTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
const (
activeTenant = uint64(26080007) // 当前工作区(无培训档案)
archiveTenant = uint64(100) // 员工档案所在空间
userID = "user-1"
)
h := NewHandler(&stubTenantResolution{resolved: archiveTenant}, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
seedAuthSession(c, activeTenant, userID)
h.TrainingTenantResolution()(c)
require.NotNil(t, c.Request)
assert.Equal(t, archiveTenant, c.GetUint64(trainingTenantContextKey))
ctxTenant, ok := types.TenantIDFromContext(c.Request.Context())
require.True(t, ok)
assert.Equal(t, archiveTenant, ctxTenant, "执行租户应回落到培训档案空间")
// caller 身份保持当前工作区:授权口径(空间 RBAC / 知识库共享解析)不受回落影响。
caller := types.CallerFromContext(c.Request.Context())
assert.Equal(t, activeTenant, caller.TenantID)
assert.Equal(t, userID, caller.UserID)
}
// TestTrainingTenantResolutionKeepsActiveTenant 当前空间已有培训档案(或解析
// 未回落)时,行为与升级前一致:租户不变化。
func TestTrainingTenantResolutionKeepsActiveTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
const activeTenant = uint64(300)
h := NewHandler(&stubTenantResolution{resolved: activeTenant}, nil)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
seedAuthSession(c, activeTenant, "user-2")
h.TrainingTenantResolution()(c)
require.NotNil(t, c.Request)
assert.Equal(t, activeTenant, c.GetUint64(trainingTenantContextKey))
ctxTenant, ok := types.TenantIDFromContext(c.Request.Context())
require.True(t, ok)
assert.Equal(t, activeTenant, ctxTenant)
}
+4 -1
View File
@@ -24,7 +24,10 @@ func RegisterTrainingRoutes(r *gin.RouterGroup, h *training.Handler, g *rbacGuar
// trainingGroup 之外直挂 v1;静态段先于 :key 参数段注册。常量是含 /api/v1
// 的全路径(noAuthAPI 白名单与企微 footer 共用),此处挂 v1 组剥掉前缀。
r.GET(strings.TrimPrefix(utils.TrainingTemplateSignedFilePath, "/api/v1"), h.DownloadTrainingTemplateSigned)
trainingGroup := r.Group("/training", g.Viewer())
// TrainingTenantResolution(000160):培训域数据空间按员工档案归属解析 ——
// 当前空间无培训档案但组织中心有在职档案的用户,培训读写回落到档案所在
// 空间;同一组织的人员在任意工作区都能参与企业培训(须在 Viewer 守卫之后)。
trainingGroup := r.Group("/training", g.Viewer(), h.TrainingTenantResolution())
{
// ---- 我的档案(角色决定工作台渲染) ----
trainingGroup.GET("/members/me", h.Me)
+19 -1
View File
@@ -29,6 +29,13 @@ type TrainingListQuery struct {
Keyword string
Page int
PageSize int
// 课程管理学员目录口径(000160,scope=catalog 时 handler 注入):
// CatalogOnly 仅返回已发布课程,且适合人员须覆盖调用方 ——
// suitable='全部' 或 =调用方部门名;未设置适合人员的存量课程沿用
// 原部门范围口径(所属部门为空=全员,否则须与调用方部门一致)。
CatalogOnly bool
CatalogDeptID string
CatalogDeptName string
}
// TrainingRepository 培训域数据访问(按域分组的方法集合)。
@@ -42,6 +49,9 @@ type TrainingRepository interface {
// 等场景高频只读);部门与名册管理走 OrgCenterRepository。
GetMember(ctx context.Context, tenantID uint64, id string) (*types.TrainingMember, error)
GetMemberByUserID(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
// FindArchiveTenantID 跨租户定位用户最早在职员工档案(org_employees)的租户
// (000160 培训数据空间解析的回退依据;无档案返回 0,nil)。
FindArchiveTenantID(ctx context.Context, userID string) (uint64, error)
// ListLecturers/ListPosts 需求提报表单的下拉数据源(讲师名册/实际岗位)。
ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error)
ListPosts(ctx context.Context, tenantID uint64) ([]string, error)
@@ -83,6 +93,8 @@ 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)
// FindCourseLibraryByName 按课程名称精准查找课程条目(000158 需求侧课程自动匹配)。
FindCourseLibraryByName(ctx context.Context, tenantID uint64, name string) (*types.TrainingCourseLibrary, error)
CreateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
UpdateCourseLibraryItem(ctx context.Context, item *types.TrainingCourseLibrary) error
// UpdateCourseLibraryPublishStatus 更新课程条目发布状态(000154:发布/下线)。
@@ -102,6 +114,8 @@ type TrainingRepository interface {
ListEnrollments(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error)
// CountEnrolledMembersByCourse 各课程应到人数(跨场次名单去重成员数)。
CountEnrolledMembersByCourse(ctx context.Context, tenantID uint64) (map[string]int, error)
// CountEnrolledMembersByCourseID 单课程场次学员名单人数(发布必填校验,000161)。
CountEnrolledMembersByCourseID(ctx context.Context, tenantID uint64, courseID string) (int, error)
// CourseStudyStats 按课程聚合签到/线上学习/考试参与成员(课程管理列表学习/考试状态列)。
CourseStudyStats(ctx context.Context, tenantID uint64) (map[string]*types.TrainingCourseStudyStats, error)
// CourseReporterDeptNames 各课程上报部门名(课程创建人所属部门,联查 org_employees/org_depts)。
@@ -265,6 +279,9 @@ type TrainingService interface {
SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error)
// CurrentMember 当前用户的培训档案(角色/部门),前端按其渲染工作台。
CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error)
// ResolveTrainingTenant 企业培训数据空间解析(000160):当前空间有培训档案
// 用当前空间;否则回退到最早在职员工档案所在空间;都没有维持当前空间。
ResolveTrainingTenant(ctx context.Context, activeTenantID uint64, userID string) (uint64, error)
// 计划域
ListDemands(ctx context.Context, tenantID uint64, q *TrainingListQuery) ([]*types.TrainingDemand, int64, error)
@@ -272,7 +289,8 @@ type TrainingService interface {
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)
// ImportDemands 批量导入需求;返回导入行与自动新增的待核验课程数(000158)。
ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, int, error)
ConfirmDemand(ctx context.Context, tenantID uint64, id string, updaterID string) (*types.TrainingDemand, error)
DeleteDemand(ctx context.Context, tenantID uint64, id string) error
// ListLecturers/ListPosts 需求提报表单下拉数据源(讲师/岗位)。
+17 -12
View File
@@ -363,16 +363,20 @@ type TrainingDemand struct {
TenantID uint64 `json:"tenant_id" gorm:"not null;index"`
Year int `json:"year" gorm:"not null;index"`
// 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:''"`
Category string `json:"category" gorm:"type:varchar(32);default:''"`
SessionCount int `json:"session_count" gorm:"default:1"`
Location string `json:"location" gorm:"type:varchar(128);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
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"`
// LibraryCourseID 需求所填课程自动匹配的课程管理条目 id(000158):填报/导入时
// 按课程名称精准查找,命中回填;未命中自动新增该课程(待核验)后回填,确认转
// 月培训计划时据此关联(存量数据无值时回退同名扫描兜底)。
LibraryCourseID string `json:"library_course_id" gorm:"type:varchar(36);default:''"`
Plant string `json:"plant" gorm:"type:varchar(64);default:''"`
Category string `json:"category" gorm:"type:varchar(32);default:''"`
SessionCount int `json:"session_count" gorm:"default:1"`
Location string `json:"location" gorm:"type:varchar(128);default:''"`
PostScope string `json:"post_scope" gorm:"type:varchar(255);default:''"`
LecturerID string `json:"lecturer_id" gorm:"type:varchar(36);default:''"`
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效,讲师列展示)。
LecturerExternal string `json:"lecturer_external" gorm:"type:varchar(64);default:''"`
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
@@ -591,8 +595,9 @@ type TrainingCourseLibrary struct {
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:''"`
// SuitableMembers 适合人员(000159 部门多选口径):归属部门名用「、」连接
// (支持多选)或「全部」=全员;存量自由文本兼容,匹配时逗号/分号归一为「、」。
SuitableMembers string `json:"suitable_members" gorm:"type:varchar(512);default:''"`
// Category 分类(配置中心 course_category_dict 可配,预设之外支持手动输入保存)。
Category string `json:"category" gorm:"type:varchar(64);default:''"`
// Type 类型(required 必修课/elective 选修课)。