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:
1 parent
3c8b595064
commit
0819f8c4d1
24 files changed
+1084
-202
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user