package service import ( "context" "encoding/json" "fmt" "strings" "time" "academy/internal/errors" "academy/internal/integrations/oa" "academy/internal/logger" "academy/internal/types" "academy/internal/types/interfaces" "github.com/google/uuid" "gorm.io/gorm" ) // trainingService 培训业务服务。实现拆分在 training.go / training_course.go / // training_exam.go / training_kb.go 四个文件。确定性业务规则(签到异常/组卷/ // 滚动/判分)在此层,不调 LLM;LLM 类能力(打标/归因/问答)由调度器与 Agent 侧接通。 type trainingService struct { repo interfaces.TrainingRepository // kbService / knowledgeSvc 用于企业培训与知识库打通: // 系统默认课件/题库库的 ensure 创建与文件同步入库。 kbService interfaces.KnowledgeBaseService knowledgeSvc interfaces.KnowledgeService // org 组织中心:部门/员工档案为租户级共享数据,职称角色按 // module_key='training' 绑定在员工档案上(见 orgcenter.go)。 org interfaces.OrgCenterService // fileSvc 视频类课件的原始文件存取:视频不入知识库解析链路, // 落 file_key 由 /training/materials/:id/file 流式取回。 fileSvc interfaces.FileService // models 模型服务:AI课程分析按租户默认对话模型生成汇总报告, // 未配置模型时回退规则引擎摘要(见 training_ai.go)。 models interfaces.ModelService // chunkSvc 分块服务:AI 课件生成试题时读课件的知识库文本分块(见 training_question_gen.go)。 chunkSvc interfaces.ChunkService // db 供 OA 企微 userid 同步直查 org_employees(见 training_scheduler 之外的 oa 集成)。 db *gorm.DB // users 平台用户服务:企微扫码免登以绑定身份签发平台 JWT(签到即自动登录, // 2026-11 需求,见 training_wecom_oauth.go)。 users interfaces.UserService // wecomOAuth 企微网页授权后端(容器注入 wecompush 适配,本层不引 internal/im)。 wecomOAuth WecomOAuthBackend } // NewTrainingService constructs the production training service. func NewTrainingService(repo interfaces.TrainingRepository, kbService interfaces.KnowledgeBaseService, knowledgeSvc interfaces.KnowledgeService, org interfaces.OrgCenterService, fileSvc interfaces.FileService, models interfaces.ModelService, chunkSvc interfaces.ChunkService, db *gorm.DB, users interfaces.UserService, wecomOAuth WecomOAuthBackend) interfaces.TrainingService { return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db, users: users, wecomOAuth: wecomOAuth} } // --------------------------------------------------------------------------- // 内部工具 // --------------------------------------------------------------------------- func trainingNewID() string { return uuid.New().String() } // --------------------------------------------------------------------------- // 唯一编号(000153,前缀+年月+流水,租户内递增) // 编号计数器失败时 fail-open(记录日志,编号留空),不阻断主流程。 // --------------------------------------------------------------------------- // nextTrainingCode 经计数器取下一流水并按 format 拼业务编号。 func (s *trainingService) nextTrainingCode(ctx context.Context, tenantID uint64, key string, format func(int64) string) string { value, err := s.repo.NextCodeValue(ctx, tenantID, key) if err != nil { logger.Error(ctx, "Failed to allocate training code", err, "key", key) return "" } return format(value) } // nextDemandCode 年计划编号:AP--####(按年分段)。 func (s *trainingService) nextDemandCode(ctx context.Context, tenantID uint64, year int) string { return s.nextTrainingCode(ctx, tenantID, fmt.Sprintf("AP:%d", year), func(v int64) string { return fmt.Sprintf("AP-%d-%04d", year, v) }) } // nextMonthPlanCode 月度计划编号:MP--####(按授课月份分段)。 func (s *trainingService) nextMonthPlanCode(ctx context.Context, tenantID uint64, year, month int) string { key := fmt.Sprintf("MP:%04d%02d", year, month) return s.nextTrainingCode(ctx, tenantID, key, func(v int64) string { return fmt.Sprintf("MP-%04d%02d-%04d", year, month, v) }) } // nextCourseLibraryCode 课程编号:CRS-####(租户内流水)。 func (s *trainingService) nextCourseLibraryCode(ctx context.Context, tenantID uint64) string { return s.nextTrainingCode(ctx, tenantID, "CRS", func(v int64) string { return fmt.Sprintf("CRS-%04d", v) }) } // nextQuestionBankCode 试题库编号:QB-####(租户内流水)。 func (s *trainingService) nextQuestionBankCode(ctx context.Context, tenantID uint64) string { return s.nextTrainingCode(ctx, tenantID, "QB", func(v int64) string { return fmt.Sprintf("QB-%04d", v) }) } // monthPlanYearMonth 从课程授课时间(teach_time,YYYY-MM 或 YYYY-MM-DD HH:mm) // 提取计划编号分段年月;解析失败回退当前年月。 func monthPlanYearMonth(teachTime string, now time.Time) (int, int) { if len(teachTime) >= 7 { var year, month int if _, err := fmt.Sscanf(teachTime[:7], "%d-%d", &year, &month); err == nil && year > 0 && month >= 1 && month <= 12 { return year, month } } return now.Year(), int(now.Month()) } func trainingJSONFromSlice(items []string) types.JSON { if len(items) == 0 { return types.JSON([]byte("[]")) } data, err := json.Marshal(items) if err != nil { return types.JSON([]byte("[]")) } return types.JSON(data) } func trainingJSONFromMap(items map[string]string) types.JSON { if len(items) == 0 { return types.JSON([]byte("{}")) } data, err := json.Marshal(items) if err != nil { return types.JSON([]byte("{}")) } return types.JSON(data) } func trainingJSONMap(data []byte) map[string]interface{} { out := map[string]interface{}{} if len(data) == 0 { return out } _ = json.Unmarshal(data, &out) return out } func trainingJSONFloat(m map[string]interface{}, key string, fallback float64) float64 { if v, ok := m[key].(float64); ok { return v } return fallback } // ruleFloat 读取数值型规则项,缺省走 fallback。 func (s *trainingService) ruleFloat(ctx context.Context, tenantID uint64, key, field string, fallback float64) float64 { cfg, err := s.repo.GetRuleConfig(ctx, tenantID, key) if err != nil || cfg == nil { return fallback } return trainingJSONFloat(trainingJSONMap(cfg.RuleValue), field, fallback) } // --------------------------------------------------------------------------- // 组织与成员(部门/员工档案为共享组织中心数据,此处仅做培训视角的委托与绑定) // --------------------------------------------------------------------------- // ListDepts returns the department tree (组织中心共享数据)。 func (s *trainingService) ListDepts(ctx context.Context, tenantID uint64) ([]*types.TrainingDept, error) { return s.org.ListDepts(ctx, tenantID) } // SaveDept creates or updates one department node (组织中心共享数据)。 func (s *trainingService) SaveDept(ctx context.Context, tenantID uint64, dept *types.TrainingDept) (*types.TrainingDept, error) { return s.org.SaveDept(ctx, tenantID, dept) } // DeleteDept soft-deletes one department node (组织中心共享数据)。 func (s *trainingService) DeleteDept(ctx context.Context, tenantID uint64, id string) error { return s.org.DeleteDept(ctx, tenantID, id) } // ListMembers returns a page of member profiles; roles 展示字段来自 // module_key='training' 的模块绑定。 func (s *trainingService) ListMembers(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingMember, int64, error) { oq := &types.OrgListQuery{} if q != nil { oq.DeptID = q.DeptID oq.Keyword = q.Keyword oq.Page = q.Page oq.PageSize = q.PageSize } return s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, oq) } // ImportMembers bulk-imports member profiles (Excel/企微同步前置)。 // 员工档案入组织中心(部门必填校验在 org 服务);职称角色缺省学员, // 写入 module_key='training' 绑定。 func (s *trainingService) ImportMembers(ctx context.Context, tenantID uint64, members []*types.TrainingMember, updaterID string) (int, error) { if len(members) == 0 { return 0, errors.NewBadRequestError("导入名单为空") } count, err := s.org.ImportEmployees(ctx, tenantID, members) if err != nil { return 0, err } // 导入后按 (tenant,user_id) 取回档案 id,确保培训绑定行落到正确员工。 for i := range members { emp, err := s.org.GetEmployeeByUserID(ctx, tenantID, members[i].UserID) if err != nil { continue } roles := members[i].OrgRoleList() if len(roles) == 0 { roles = []string{types.TrainingRoleTrainee} } _, _ = s.org.PutModuleMember(ctx, tenantID, &types.OrgModuleMember{ ModuleKey: types.OrgModuleTraining, EmployeeID: emp.ID, Roles: trainingJSONFromSlice(roles), }) } logger.Infof(ctx, "[Training] members imported, tenant=%d count=%d operator=%s", tenantID, len(members), updaterID) return count, nil } // UpdateMemberRoles updates the member's training module roles. // 角色按字典白名单校验:仅接受职称角色字典内的 key + trainee, // 避免拼错的 key 被静默存入后鉴权永远不命中。 func (s *trainingService) UpdateMemberRoles(ctx context.Context, tenantID uint64, id string, roles []string, updaterID string) (*types.TrainingMember, error) { member, err := s.repo.GetMember(ctx, tenantID, id) if err != nil { return nil, errors.NewNotFoundError("员工档案不存在") } dictKeys := make(map[string]bool, 8) for _, def := range s.RoleDict(ctx, tenantID) { dictKeys[def.Key] = true } dictKeys[string(types.TrainingRoleTrainee)] = true for _, r := range roles { if !dictKeys[r] { return nil, errors.NewBadRequestError(fmt.Sprintf("未知角色: %s,请先在配置中心维护角色字典", r)) } } // 学员角色永远保留(全员皆为学员)。 if !types.HasTrainingRole(roles, types.TrainingRoleTrainee) { roles = append(roles, types.TrainingRoleTrainee) } if _, err := s.org.PutModuleMember(ctx, tenantID, &types.OrgModuleMember{ ModuleKey: types.OrgModuleTraining, EmployeeID: member.ID, Roles: trainingJSONFromSlice(roles), }); err != nil { return nil, err } _ = updaterID return s.trainingMemberWithRoles(ctx, tenantID, member) } // UpdateMemberWecomUserid maintains the employee's WeCom userid — the push // target of training reminders (empty string unbinds). Read-modify-write via // GetEmployee so the other archive fields survive org.UpdateEmployee's // full-column update. func (s *trainingService) UpdateMemberWecomUserid(ctx context.Context, tenantID uint64, id, wecomUserid string) (*types.TrainingMember, error) { employee, err := s.org.GetEmployee(ctx, tenantID, id) if err != nil { return nil, errors.NewNotFoundError("员工档案不存在") } employee.WecomUserid = strings.TrimSpace(wecomUserid) if _, err := s.org.UpdateEmployee(ctx, tenantID, employee); err != nil { return nil, err } return s.trainingMemberWithRoles(ctx, tenantID, employee) } // SyncWecomUseridsFromOA pulls workcode → WeCom userid mappings from the OA // directory and (apply) writes org_employees.wecom_userid, porting the HXPH // sync (preview-first, conflict-guarded). See internal/integrations/oa. func (s *trainingService) SyncWecomUseridsFromOA(ctx context.Context, tenantID uint64, apply bool) (*oa.SyncSummary, error) { if s.db == nil { return nil, errors.NewBadRequestError("数据库连接未初始化") } return oa.SyncWecomUseridsFromOA(ctx, s.db, tenantID, apply) } // CurrentMember returns the caller's training profile; absent profiles get a // trainee-only implicit profile so学员端 works before档案导入. func (s *trainingService) CurrentMember(ctx context.Context, tenantID uint64, userID string) (*types.TrainingMember, error) { member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err == nil { return s.trainingMemberWithRoles(ctx, tenantID, member) } return &types.TrainingMember{ TenantID: tenantID, UserID: userID, Roles: trainingJSONFromSlice([]string{types.TrainingRoleTrainee}), Status: "active", }, 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) if err == nil && binding != nil { member.Roles = binding.Roles } else { member.Roles = trainingJSONFromSlice([]string{}) } return member, nil } // ListPlatformUsers 平台用户列表(成员导入选择器数据源,组织中心共享)。 func (s *trainingService) ListPlatformUsers(ctx context.Context, tenantID uint64) ([]*types.TrainingUserInfo, error) { return s.org.ListTenantUsers(ctx, tenantID) } // --------------------------------------------------------------------------- // 计划域 // --------------------------------------------------------------------------- // ListDemands returns a page of demands. func (s *trainingService) ListDemands(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingDemand, int64, error) { return s.repo.ListDemands(ctx, tenantID, q) } // ListDemandYears returns distinct demand years (desc) for the year filter. func (s *trainingService) ListDemandYears(ctx context.Context, tenantID uint64, deptID string) ([]int, error) { return s.repo.ListDemandYears(ctx, tenantID, deptID) } // GetDemand fetches one demand. func (s *trainingService) GetDemand(ctx context.Context, tenantID uint64, id string) (*types.TrainingDemand, error) { return s.repo.GetDemand(ctx, tenantID, id) } // ListLecturers returns the lecturer roster for the demand form picker. func (s *trainingService) ListLecturers(ctx context.Context, tenantID uint64) ([]*types.TrainingLecturerOption, error) { return s.repo.ListLecturers(ctx, tenantID) } // ListPosts returns the distinct posts of active members for the demand form picker. func (s *trainingService) ListPosts(ctx context.Context, tenantID uint64) ([]string, error) { return s.repo.ListPosts(ctx, tenantID) } // EnsureLecturerRole 讲师自动授权:每一位员工都可能是讲师,课程/需求选定讲师后 // 自动补齐培训模块 lecturer 角色绑定(已有角色则幂等跳过;档案缺失 fail-open)。 func (s *trainingService) EnsureLecturerRole(ctx context.Context, tenantID uint64, userID string) error { if userID == "" { return nil } member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID) if err != nil || member == nil { return nil } existing, err := s.org.GetModuleMember(ctx, tenantID, "training", member.ID) if err == nil && existing != nil { var roles []string if json.Unmarshal(existing.Roles, &roles) == nil { for _, r := range roles { if r == "lecturer" { return nil } } roles = append(roles, "lecturer") updated, _ := json.Marshal(roles) _, err = s.org.PutModuleMember(ctx, tenantID, &types.OrgModuleMember{ ID: existing.ID, ModuleKey: "training", EmployeeID: member.ID, Roles: types.JSON(updated), }) return err } } _, err = s.org.PutModuleMember(ctx, tenantID, &types.OrgModuleMember{ ModuleKey: "training", EmployeeID: member.ID, Roles: types.JSON([]byte(`["lecturer"]`)), }) return err } // 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("课程名称不能为空") } if demand.ExpectMonth < 0 || demand.ExpectMonth > 12 { return nil, errors.NewBadRequestError("期望月份不合法") } // 讲师口径互斥:系统员工(lecturer_id)优先,外部姓名(lecturer_external)仅在无 id 时生效。 if demand.LecturerID != "" { demand.LecturerExternal = "" } if demand.Year <= 0 { demand.Year = time.Now().Year() } if demand.ID != "" { existing, err := s.repo.GetDemand(ctx, tenantID, demand.ID) if err != nil { return nil, errors.NewNotFoundError("需求不存在") } if existing.Status == types.TrainingDemandConfirmed { return nil, errors.NewBadRequestError("已确认的需求不可编辑") } // 编辑保留原课程关联(000158):课程名未变时跳过重匹配,匹配失败时不 // 清空已有关联(UpdateDemand 全量更新,零值会误清)。 prevLibraryCourseID = existing.LibraryCourseID prevCourseName = existing.CourseName } // 字段校验(规则引擎):缺项给出可执行提示,AI 语义校验由二期接手。 // 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。 // 核验状态默认「待核验」:填报/编辑不自动通过,统一由经理核验确认。 msgs := []string{} if demand.DeptID == "" { msgs = append(msgs, "未指定部门") } demand.CheckMsg = "" for i, m := range msgs { if i > 0 { demand.CheckMsg += ";" } demand.CheckMsg += m } demand.CheckStatus = types.TrainingCheckPending if demand.Status == "" { 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, // 适合人员备注(000165):需求「适合人员」同步落到课程管理备注字段。 PostScope: 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 // 年计划编号(AP--####,创建时生成;计数器失败留空不阻断)。 demand.Code = s.nextDemandCode(ctx, tenantID, demand.Year) if err := s.repo.CreateDemand(ctx, demand); err != nil { return nil, err } return demand, nil } demand.TenantID = tenantID if err := s.repo.UpdateDemand(ctx, demand); err != nil { return nil, err } return demand, nil } // ImportDemands batch-imports demands (调研表在线化/邮件替代)。 // 返回导入行与自动新增的待核验课程数(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, 0, errors.NewBadRequestError("导入数据为空") } // 课程校验批内去重(000158):同名行只查/建一次,其余行复用条目 id。 courseCache := map[string]string{} coursesCreated := 0 for i := range demands { demands[i].ID = trainingNewID() demands[i].TenantID = tenantID demands[i].SubmitterID = updaterID if demands[i].Year <= 0 { demands[i].Year = time.Now().Year() } // 年计划编号(批量导入逐行生成,同年前缀分段递增)。 demands[i].Code = s.nextDemandCode(ctx, tenantID, demands[i].Year) if demands[i].Status == "" { demands[i].Status = types.TrainingDemandSubmitted } // 与 SaveDemand 同口径的缺项提示,方便导入后在列表中补齐再确认。 // 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。 // 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。 // 讲师口径互斥与 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, // 适合人员备注(000165):批量导入同样同步到课程管理备注字段。 PostScope: 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, 0, err } return demands, coursesCreated, nil } // ConfirmDemand marks one demand confirmed and auto-aggregates it into the // annual schedule (按来源需求判重,不重复生成)。 // 先落排期行再改状态:排期落库失败则确认一并失败,避免出现"已确认但无排期"。 func (s *trainingService) ConfirmDemand(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingDemand, error) { demand, err := s.repo.GetDemand(ctx, tenantID, id) if err != nil { return nil, errors.NewNotFoundError("需求不存在") } count, err := s.repo.CountAnnualPlanBySource(ctx, tenantID, id) if err != nil { return nil, err } if count == 0 { month := demand.ExpectMonth if month < 1 { month = 1 } if err := s.repo.BatchCreateAnnualPlans(ctx, []*types.TrainingAnnualPlan{{ ID: trainingNewID(), TenantID: tenantID, Year: demand.Year, DeptID: demand.DeptID, CourseName: demand.CourseName, Hours: demand.Hours, PlanMonth: month, SourceDemandID: demand.ID, Status: "planned", }}); err != nil { return nil, err } } demand.Status = types.TrainingDemandConfirmed demand.CheckStatus = types.TrainingCheckPassed if err := s.repo.UpdateDemand(ctx, demand); err != nil { return nil, err } _ = updaterID return demand, nil } // DeleteDemand soft-deletes one unconfirmed demand. // 状态「已确认」的需求不可删除,避免误删已纳入年度排期的口径;仅超级管理员 // (bySuperAdmin:super_admin 职称角色或空间 Owner 兜底)放开终态删除。 func (s *trainingService) DeleteDemand(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error { demand, err := s.repo.GetDemand(ctx, tenantID, id) if err != nil { return errors.NewNotFoundError("需求不存在") } if demand.Status == types.TrainingDemandConfirmed && !bySuperAdmin { return errors.NewBadRequestError("已确认的需求不可删除") } return s.repo.DeleteDemand(ctx, tenantID, id) } // GenerateAnnualPlan aggregates confirmed demands into the annual schedule. // 按来源需求判重,已有排期的需求跳过(手动兜底重跑也不会产生重复行)。 func (s *trainingService) GenerateAnnualPlan(ctx context.Context, tenantID uint64, year int, updaterID string) ([]*types.TrainingAnnualPlan, error) { demands, _, err := s.repo.ListDemands(ctx, tenantID, &interfaces.TrainingListQuery{Year: year, PageSize: 1000}) if err != nil { return nil, err } plans := make([]*types.TrainingAnnualPlan, 0, len(demands)) for _, d := range demands { if d.Status != types.TrainingDemandConfirmed { continue } exists, err := s.repo.CountAnnualPlanBySource(ctx, tenantID, d.ID) if err == nil && exists > 0 { continue } month := d.ExpectMonth if month < 1 { month = 1 } plans = append(plans, &types.TrainingAnnualPlan{ ID: trainingNewID(), TenantID: tenantID, Year: year, DeptID: d.DeptID, CourseName: d.CourseName, Hours: d.Hours, PlanMonth: month, SourceDemandID: d.ID, Status: "planned", }) } if len(plans) == 0 { return nil, errors.NewBadRequestError("没有可汇总的年度需求(需确认且未生成过排期)") } if err := s.repo.BatchCreateAnnualPlans(ctx, plans); err != nil { return nil, err } logger.Infof(ctx, "[Training] annual plan generated, tenant=%d year=%d plans=%d operator=%s", tenantID, year, len(plans), updaterID) return plans, nil } // ListAnnualPlans returns the annual schedule. func (s *trainingService) ListAnnualPlans(ctx context.Context, tenantID uint64, year int) ([]*types.TrainingAnnualPlan, error) { return s.repo.ListAnnualPlans(ctx, tenantID, year) } // DeptDemandProgress returns demand collection progress per department. func (s *trainingService) DeptDemandProgress(ctx context.Context, tenantID uint64, year int) ([]*types.TrainingDeptProgress, error) { rows, err := s.repo.DeptDemandProgress(ctx, tenantID, year) if err != nil { return nil, err } for _, row := range rows { if row.Total > 0 { row.Percent = int(float64(row.Done) / float64(row.Total) * 100) } } return rows, nil } // ListMonthPlans returns month plans. func (s *trainingService) ListMonthPlans(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingMonthPlan, error) { return s.repo.ListMonthPlans(ctx, tenantID, q) } // SaveMonthPlan creates or updates one month plan. func (s *trainingService) SaveMonthPlan(ctx context.Context, tenantID uint64, plan *types.TrainingMonthPlan) (*types.TrainingMonthPlan, error) { if plan.Title == "" { return nil, errors.NewBadRequestError("排课标题不能为空") } if plan.Year <= 0 { plan.Year = time.Now().Year() } if plan.Month < 1 || plan.Month > 12 { return nil, errors.NewBadRequestError("月份不合法") } if plan.Status == "" { plan.Status = types.TrainingMonthPlanDraft } if plan.ID == "" { plan.ID = trainingNewID() plan.TenantID = tenantID if err := s.repo.CreateMonthPlan(ctx, plan); err != nil { return nil, err } return plan, nil } plan.TenantID = tenantID if err := s.repo.UpdateMonthPlan(ctx, plan); err != nil { return nil, err } return plan, nil } // ApproveMonthPlan transitions a plan: pass → approved; adjust/reject → // rejected with reason (主管审批月度排期)。 func (s *trainingService) ApproveMonthPlan(ctx context.Context, tenantID uint64, id, action, reason, approverID string) (*types.TrainingMonthPlan, error) { plan, err := s.repo.GetMonthPlan(ctx, tenantID, id) if err != nil { return nil, errors.NewNotFoundError("排期不存在") } if plan.Status != types.TrainingMonthPlanSubmitted && plan.Status != types.TrainingMonthPlanDraft { return nil, errors.NewBadRequestError("当前状态不允许审批") } now := time.Now() switch action { case "pass": plan.Status = types.TrainingMonthPlanApproved plan.ApproverID = approverID plan.ApprovedAt = &now plan.RejectReason = "" case "adjust", "reject": plan.Status = types.TrainingMonthPlanRejected plan.ApproverID = approverID plan.RejectReason = reason default: return nil, errors.NewBadRequestError("审批动作不合法") } if err := s.repo.UpdateMonthPlan(ctx, plan); err != nil { return nil, err } return plan, nil } // RollMonthPlans rolls unfinished courses of (fromYear, fromMonth) into the // next month, pinned on top; two consecutive misses escalate (滚动规则)。 func (s *trainingService) RollMonthPlans(ctx context.Context, tenantID uint64, fromYear, fromMonth int, operatorID string) (int, error) { unfinished, err := s.repo.UnfinishedEnrollments(ctx, tenantID, fromYear, fromMonth) if err != nil { return 0, err } if len(unfinished) == 0 { return 0, nil } // 汇总未完成报名涉及的场次。 sessionIDs := map[string]struct{}{} for _, e := range unfinished { sessionIDs[e.SessionID] = struct{}{} } nextYear, nextMonth := fromYear, fromMonth+1 if nextMonth > 12 { nextYear, nextMonth = fromYear+1, 1 } rolled := 0 for sid := range sessionIDs { session, err := s.repo.GetSession(ctx, tenantID, sid) if err != nil { continue } courseName := "" if course, err := s.repo.GetCourse(ctx, tenantID, session.CourseID); err == nil { courseName = course.Name } if courseName == "" { courseName = fmt.Sprintf("未完成课程 %s", sid) } // 幂等:同月同名滚动目标已存在则跳过。 if count, err := s.repo.CountMonthPlansRolled(ctx, tenantID, nextYear, nextMonth, courseName); err == nil && count > 0 { continue } rollTimes := 1 if session.MonthPlanID != "" { if src, err := s.repo.GetMonthPlan(ctx, tenantID, session.MonthPlanID); err == nil { rollTimes = src.RollTimes + 1 } } plan := &types.TrainingMonthPlan{ ID: trainingNewID(), TenantID: tenantID, Year: nextYear, Month: nextMonth, Title: courseName, Status: types.TrainingMonthPlanDraft, RollFromID: session.ID, RollTimes: rollTimes, Escalated: rollTimes >= 2, // 连续两月未完成升级并抄送人事 SubmitterID: operatorID, } if err := s.repo.CreateMonthPlan(ctx, plan); err != nil { continue } rolled++ } logger.Infof(ctx, "[Training] month plans rolled, tenant=%d from=%d-%02d rolled=%d operator=%s", tenantID, fromYear, fromMonth, rolled, operatorID) return rolled, nil }