推送域(000155):
- 广播通知支持 link_url:demand_collect 场景自动签发教育训练需求表模板
匿名下载直链(HMAC token,20 天有效,免登录路由),企微消息尾部拼
「下载模板 + 查看更多详情」链接;站内文本保持纯文本不受影响
- 配置中心新增「推送链接基址」(notify_link_base_url,多入口/内外网部署固定
权威地址,留空跟随推送人访问地址)与「年培训计划收集推送文案」
(demand_collect_*,{year} 渲染收集年度);空标题/内容按模板回落渲染
- 迁移 000155:tr_training_notifications 增 link_url/link_token 列
课程管理:
- 修复点【发布/下线】报「不支持的操作」:动作取值兼容字面量路由(FullPath
末段)与 :action 通配两种注册形态
- 列表新增「创建人」列:creator_id 联查 users 带出姓名,导出 Excel 同步;
新增课程「所属部门」默认当前登录用户所在部门
- 导入加固:表头归一化 + 别名模糊匹配(兼容内置模板/旧口径/自定义模板变体);
导入与新增行支持按部门名兜底解析为 id(前端名册未命中时传 owner_dept_name)
年培训计划:
- 需求列表新增「创建人/创建时间」列(submitter_id 联查 users 带出姓名)
- 收集模板调整:下载时动态删除「培训费用(RMB)」列(旧版自定义模板同步归一,
右侧列/合并/下拉随删列平移);备注右侧追加「调研维度/培训策划要求」说明列
(合并至数据区末行,自动换行带边框,已带说明的自定义模板不覆盖)
开发工具:
- air 热重载适配 Windows:构建收敛到 scripts/air_build.sh(规避 air 经
PowerShell 执行不支持 bash 命令替换),产物改 .exe 后缀;CGO_CFLAGS 取
持久化值并集追加,不覆盖 go env -w 的头文件包含路径
710 lines
26 KiB
Go
710 lines
26 KiB
Go
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
|
|
}
|
|
|
|
// 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) interfaces.TrainingService {
|
|
return &trainingService{repo: repo, kbService: kbService, knowledgeSvc: knowledgeSvc, org: org, fileSvc: fileSvc, models: models, chunkSvc: chunkSvc, db: db}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 内部工具
|
|
// ---------------------------------------------------------------------------
|
|
|
|
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-<year>-####(按年分段)。
|
|
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-<YYYYMM>-####(按授课月份分段)。
|
|
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
|
|
}
|
|
|
|
// 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) {
|
|
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("已确认的需求不可编辑")
|
|
}
|
|
}
|
|
// 字段校验(规则引擎):缺项给出可执行提示,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
|
|
}
|
|
|
|
if demand.ID == "" {
|
|
demand.ID = trainingNewID()
|
|
demand.TenantID = tenantID
|
|
// 年计划编号(AP-<year>-####,创建时生成;计数器失败留空不阻断)。
|
|
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 (调研表在线化/邮件替代)。
|
|
func (s *trainingService) ImportDemands(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand, updaterID string) ([]*types.TrainingDemand, error) {
|
|
if len(demands) == 0 {
|
|
return nil, errors.NewBadRequestError("导入数据为空")
|
|
}
|
|
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 同口径的缺项提示,方便导入后在列表中补齐再确认。
|
|
// 口径对齐需求表模板后,人数/课时不再采集,仅校验部门。
|
|
// 核验状态默认「待核验」:导入不自动通过,统一由经理核验确认。
|
|
msgs := []string{}
|
|
if demands[i].DeptID == "" {
|
|
msgs = append(msgs, "未指定部门")
|
|
}
|
|
demands[i].CheckMsg = strings.Join(msgs, ";")
|
|
demands[i].CheckStatus = types.TrainingCheckPending
|
|
}
|
|
if err := s.repo.BatchCreateDemands(ctx, demands); err != nil {
|
|
return nil, err
|
|
}
|
|
return demands, 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.
|
|
// 状态「已确认」的需求不可删除,避免误删已纳入年度排期的口径。
|
|
func (s *trainingService) DeleteDemand(ctx context.Context, tenantID uint64, id string) error {
|
|
demand, err := s.repo.GetDemand(ctx, tenantID, id)
|
|
if err != nil {
|
|
return errors.NewNotFoundError("需求不存在")
|
|
}
|
|
if demand.Status == types.TrainingDemandConfirmed {
|
|
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
|
|
}
|