Files
ai_academy/internal/application/service/training_course.go
T
runny 858c352991
deploy-hxtesting / build-and-deploy (push) Successful in 1m28s
fix(bug):1.帮我检查一下平台中有多少处显示部门地方这种“e10-、、、、”字样拿掉不要显示
2.月培训计划发布时授课时间默认空着点击【发布】时提示先维护授课时间,(不要默认年培训计划)
3.授课地点默认“年度计划”所设置的授课地点,如果年培训计划没有维护发布时也要必填
4.点击【发布】时要校验参加人员不能为空!默认为所属部门下的人员~
认真阅读相关代码~
2026-11-30 16:13:42 +08:00

1153 lines
48 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package service
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"academy/internal/utils"
"github.com/xuri/excelize/v2"
)
// ---------------------------------------------------------------------------
// 课程域
// ---------------------------------------------------------------------------
// ListCourses returns a page of courses.
func (s *trainingService) ListCourses(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourse, int64, error) {
courses, total, err := s.repo.ListCourses(ctx, tenantID, q)
if err != nil {
return nil, 0, err
}
// 应到人数:各课程场次名单去重汇总(fail-open,取不到时保持 0)。
if counts, aggErr := s.repo.CountEnrolledMembersByCourse(ctx, tenantID); aggErr == nil {
for _, c := range courses {
if c != nil {
c.ExpectedCount = counts[c.ID]
}
}
}
// 上报部门:课程创建人所属部门名(fail-open)。
if deptNames, aggErr := s.repo.CourseReporterDeptNames(ctx, tenantID); aggErr == nil {
for _, c := range courses {
if c != nil {
c.ReporterDeptName = deptNames[c.ID]
}
}
}
// 实/应人数与学习/考试状态:按签到 ∪ 线上学习参与、考试记录去重聚合(fail-open)。
if stats, aggErr := s.repo.CourseStudyStats(ctx, tenantID); aggErr == nil {
for _, c := range courses {
if c == nil {
continue
}
st := stats[c.ID]
if st == nil {
st = &types.TrainingCourseStudyStats{}
}
c.ActualCount = len(unionStrings(st.SignedMembers, st.StartedMembers))
c.LearningStatus = courseLearnStatus(c.ExpectedCount, st)
c.ExamStatus = courseExamStatus(c.ExpectedCount, st)
}
}
// 关联课程管理条目的发布状态(000163):月培训计划列表标注「课程已下线」。
s.attachLibraryOffline(ctx, tenantID, courses...)
return courses, total, nil
}
// attachLibraryOffline 批量回填课程关联课程管理条目的发布状态(000163):
// library_course_id 命中的条目已下线(publish_status=offline)时置
// LibraryOffline,学习入口按「该课程已下线」拦截(存量计划行保留不消失)。
// fail-open:查询失败保持零值,不阻断列表/详情。
func (s *trainingService) attachLibraryOffline(ctx context.Context, tenantID uint64, courses ...*types.TrainingCourse) {
ids := make([]string, 0, len(courses))
hit := make(map[string]bool, len(courses))
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" || hit[c.LibraryCourseID] {
continue
}
hit[c.LibraryCourseID] = true
ids = append(ids, c.LibraryCourseID)
}
if len(ids) == 0 {
return
}
statuses, err := s.repo.ListCourseLibraryStatuses(ctx, tenantID, ids)
if err != nil {
logger.Warnf(ctx, "Skip attach library offline status, tenant=%d error: %v", tenantID, err)
return
}
for _, c := range courses {
if c == nil || c.LibraryCourseID == "" {
continue
}
c.LibraryPublishStatus = statuses[c.LibraryCourseID]
c.LibraryOffline = c.LibraryPublishStatus == "offline"
}
}
// courseLearnStatus 课程学习状态:
// 无人签到且无人开始学习 → 未学习;完成人数(签到∪任务done)达到
// max(应到, 参与) → 已学习;否则 → 学习中。线下课签到即视同完成学习。
// 去重并集复用本包 unionStrings。
func courseLearnStatus(expected int, st *types.TrainingCourseStudyStats) string {
participants := unionStrings(st.SignedMembers, st.StartedMembers)
if len(participants) == 0 {
return types.TrainingLearnNotStarted
}
completed := unionStrings(st.SignedMembers, st.DoneMembers)
denominator := len(participants)
if expected > denominator {
denominator = expected
}
if len(completed) >= denominator {
return types.TrainingLearnDone
}
return types.TrainingLearnDoing
}
// courseExamStatus 课程考试状态:无考试记录 → 未考试;
// 已考人数达到 max(应到, 已考名单) → 已考试;否则 → 考试中。
func courseExamStatus(expected int, st *types.TrainingCourseStudyStats) string {
if len(st.ExamMembers) == 0 {
return types.TrainingExamNotStarted
}
denominator := len(st.ExamMembers)
if expected > denominator {
denominator = expected
}
if len(st.ExamMembers) >= denominator {
return types.TrainingExamDone
}
return types.TrainingExamTaking
}
// GetCourse returns one course.
// courseExamBank 课程考试题库解析(000153):优先取课程直连题库(course_id),
// 未绑定时回退课程管理条目下的题库(library_course_id,试题随课程管理维护)。
func (s *trainingService) courseExamBank(ctx context.Context, tenantID uint64, course *types.TrainingCourse) (*types.TrainingQuestionBank, error) {
if course == nil {
return nil, errors.NewNotFoundError("课程不存在")
}
if bank, err := s.repo.GetQuestionBankByCourse(ctx, tenantID, course.ID); err == nil && bank != nil {
return bank, nil
}
if course.LibraryCourseID == "" {
return nil, errors.NewNotFoundError("题库不存在")
}
banks, err := s.repo.GetQuestionBankByLibraryCourse(ctx, tenantID, course.LibraryCourseID)
if err != nil || len(banks) == 0 {
return nil, errors.NewNotFoundError("题库不存在")
}
return banks[0], nil
}
func (s *trainingService) GetCourse(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourse, error) {
course, err := s.repo.GetCourse(ctx, tenantID, id)
if err != nil {
return nil, errors.NewNotFoundError("课程不存在")
}
// 绑定题库即具备在线考试条件(详情页随堂考试入口与 exam_enabled 开关并联);
// 课程自身未绑定时回退课程管理条目的题库(000153)。
if bank, bankErr := s.courseExamBank(ctx, tenantID, course); bankErr == nil && bank != nil {
course.ExamReady = true
}
// 关联课程管理条目已下线时带出标记(000163):学习页据此提示
// 「该课程已下线」并拦截课件/考试入口。
s.attachLibraryOffline(ctx, tenantID, course)
return course, nil
}
// applyLibraryCourseBinding 月度计划选择课程管理课程后的信息带出与锁定(000153):
// 课程名称/类型随课程管理主数据锁定;形式(mode)为计划侧独立字段——计划形式
// 指本次培训线上办还是线下办,与课程主数据的线上课/线下课口径不同,不随课程
// 带出,由创建/调整表单自行选择;讲师 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
}
item, err := s.repo.GetCourseLibraryItem(ctx, tenantID, course.LibraryCourseID)
if err != nil || item == nil {
logger.Error(ctx, "Failed to load library course for plan binding", err, "library_course_id", course.LibraryCourseID)
return nil
}
// 锁定字段:随课程管理主数据,请求侧取值一律覆盖(形式除外,见上)。
course.Name = item.Name
course.Type = item.Type
if isCreate && (item.LecturerID != "" || item.LecturerExternal != "") {
// 新建仍随主数据带出讲师;更新路径计划侧可改(000161)。
course.LecturerID = item.LecturerID
course.LecturerExternal = item.LecturerExternal
}
if !isCreate {
return item
}
// 预填字段:仅新建时带出,后续学时/学分按月度计划维护口径可调。
if course.Hours <= 0 {
course.Hours = item.Hours
}
if course.Code == "" {
// 000163 根因修复:编号按租户流水独立生成,不再复制课程管理条目编号。
// tr_courses 有 (tenant_id, code) 唯一索引,复制 CRS-#### 后同一门课程
// 管理课程创建第二个月度计划必然撞唯一约束(500 duplicate key,
// 2026-11-25 测试环境「暂存草稿」即因此失败);计划行经 library_course_id
// 关联主数据,编号独立生成不影响带出与锁定逻辑。
// fail-open:计数器失败留空(唯一索引豁免空编号),不阻断保存。
course.Code = s.nextCourseLibraryCode(ctx, tenantID)
}
if len(course.DeptIDs) == 0 || string(course.DeptIDs) == "[]" || string(course.DeptIDs) == "null" {
if item.OwnerDeptID != "" {
deptIDs, _ := json.Marshal([]string{item.OwnerDeptID})
course.DeptIDs = types.JSON(deptIDs)
}
}
if course.PostScope == "" {
course.PostScope = item.SuitableMembers
}
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。
func (s *trainingService) attachLibraryCourseMaterial(ctx context.Context, tenantID uint64, courseID string, item *types.TrainingCourseLibrary, updaterID string) {
if item == nil {
return
}
name := item.FileName
if name == "" {
name = item.MaterialName
}
if name == "" {
return
}
kind := "doc"
if isVideoMaterialFile("", name) {
kind = "video"
}
material := &types.TrainingMaterial{
CourseID: courseID,
Kind: kind,
Name: name,
}
if item.KnowledgeID != "" {
material.KnowledgeID = item.KnowledgeID
} else {
material.FileKey = item.FileKey
}
if _, err := s.CreateMaterial(ctx, tenantID, material, updaterID); err != nil {
logger.Error(ctx, "Failed to attach library course material to plan", err, "course_id", courseID)
}
}
// SaveCourse creates or updates one course.
func (s *trainingService) SaveCourse(ctx context.Context, tenantID uint64, course *types.TrainingCourse, updaterID string) (*types.TrainingCourse, error) {
if course.Name == "" {
return nil, errors.NewBadRequestError("课程名称不能为空")
}
if course.Mode != types.TrainingCourseModeOnline && course.Mode != types.TrainingCourseModeOffline {
course.Mode = types.TrainingCourseModeOffline
}
if course.Status == "" {
course.Status = types.TrainingCourseDraft
}
if course.ID == "" {
course.ID = trainingNewID()
course.TenantID = tenantID
course.CreatorID = updaterID
// 课程管理信息带出与锁定(000153),课件资料随计划挂接(线上发布/学习页依赖)。
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, true)
s.attachLibraryCourseMaterial(ctx, tenantID, course.ID, libItem, updaterID)
// 月度计划编号(MP-<YYYYMM>-####,按授课月份分段;解析失败取当前月)。
year, month := monthPlanYearMonth(course.TeachTime, time.Now())
course.PlanCode = s.nextMonthPlanCode(ctx, tenantID, year, month)
if err := s.repo.CreateCourse(ctx, course); err != nil {
return nil, err
}
return course, nil
}
course.TenantID = tenantID
// 课程管理关联存在时锁定带出字段(000153;讲师 000161 起计划侧可改)。
libItem := s.applyLibraryCourseBinding(ctx, tenantID, course, false)
// 课程信息变更留痕:对比更新前取值,任一字段变化则落一条版本记录(fail-open,不阻断保存)。
old, err := s.repo.GetCourse(ctx, tenantID, course.ID)
if err != nil {
return nil, err
}
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)
}
return course, nil
}
// ListCourseChangeLogs returns the course's change history (newest first).
func (s *trainingService) ListCourseChangeLogs(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingCourseChangeLog, error) {
return s.repo.ListCourseChangeLogs(ctx, tenantID, courseID)
}
// ---------------------------------------------------------------------------
// 课程信息修改版本记录
// ---------------------------------------------------------------------------
// courseChange 字段级变更明细(展示用)。
type courseChange struct {
Field string `json:"field"`
Label string `json:"label"`
Old string `json:"old"`
New string `json:"new"`
}
// recordCourseChangeLog 对比新旧课程构建字段级变更明细,有变化则落一条版本记录。
func (s *trainingService) recordCourseChangeLog(ctx context.Context, tenantID uint64, courseID string, old, new *types.TrainingCourse, operatorID string) {
lecturers, _ := s.repo.ListLecturers(ctx, tenantID)
lecturerNames := make(map[string]string, len(lecturers))
for _, l := range lecturers {
lecturerNames[l.ID] = l.Name
}
depts, _ := s.org.ListDepts(ctx, tenantID)
deptNames := make(map[string]string, len(depts))
for _, d := range depts {
deptNames[d.ID] = d.Name
}
deptText := func(idsJSON types.JSON) string {
ids := []string{}
_ = json.Unmarshal(idsJSON, &ids)
names := make([]string, 0, len(ids))
for _, id := range ids {
if n := deptNames[id]; n != "" {
names = append(names, n)
}
}
return strings.Join(names, " / ")
}
blankToEmpty := func(v string) string {
if strings.TrimSpace(v) == "" {
return ""
}
return v
}
modeText := func(mode string) string {
if mode == types.TrainingCourseModeOnline {
return "线上"
}
return "线下"
}
appendChange := func(changes []courseChange, field, label, oldV, newV string) []courseChange {
if oldV == newV {
return changes
}
return append(changes, courseChange{Field: field, Label: label, Old: oldV, New: newV})
}
changes := []courseChange{}
changes = appendChange(changes, "name", "课程名称", blankToEmpty(old.Name), blankToEmpty(new.Name))
changes = appendChange(changes, "mode", "形式", modeText(old.Mode), modeText(new.Mode))
changes = appendChange(changes, "type", "类型", courseTypeLabel(old.Type), courseTypeLabel(new.Type))
changes = appendChange(changes, "hours", "学时", strconv.FormatFloat(old.Hours, 'f', -1, 64), strconv.FormatFloat(new.Hours, 'f', -1, 64))
changes = appendChange(changes, "credits", "学分", strconv.FormatFloat(old.Credits, 'f', -1, 64), strconv.FormatFloat(new.Credits, 'f', -1, 64))
changes = appendChange(changes, "lecturer_id", "讲师", lecturerNames[old.LecturerID], lecturerNames[new.LecturerID])
changes = appendChange(changes, "dept_ids", "适用部门", deptText(old.DeptIDs), deptText(new.DeptIDs))
changes = appendChange(changes, "post_scope", "适用岗位", blankToEmpty(old.PostScope), blankToEmpty(new.PostScope))
changes = appendChange(changes, "teach_time", "授课时间", blankToEmpty(old.TeachTime), blankToEmpty(new.TeachTime))
changes = appendChange(changes, "planned_time", "计划培训时间", blankToEmpty(old.PlannedTime), blankToEmpty(new.PlannedTime))
changes = appendChange(changes, "description", "课程简介", blankToEmpty(old.Description), blankToEmpty(new.Description))
if len(changes) == 0 {
return
}
changesJSON, err := json.Marshal(changes)
if err != nil {
return
}
_ = s.repo.CreateCourseChangeLog(ctx, &types.TrainingCourseChangeLog{
ID: trainingNewID(), TenantID: tenantID, CourseID: courseID,
Changes: types.JSON(changesJSON), OperatorID: operatorID,
})
}
// courseTypeLabel 类型展示文案(未知值原样返回)。
func courseTypeLabel(t string) string {
switch t {
case "required":
return "必修"
case "elective":
return "选修"
}
return t
}
// DeleteCourse soft-deletes one course.
// 已发布计划不可普通删除(避免误删已排期/已通知的计划);仅超级管理员
// (bySuperAdmin:super_admin 职称角色或空间 Owner 兜底)放开终态删除。
func (s *trainingService) DeleteCourse(ctx context.Context, tenantID uint64, id string, bySuperAdmin bool) error {
course, err := s.GetCourse(ctx, tenantID, id)
if err != nil {
return err
}
if course.Status == types.TrainingCoursePublished && !bySuperAdmin {
return errors.NewBadRequestError("已发布的培训计划不可删除,仅超级管理员可删除")
}
return s.repo.DeleteCourse(ctx, tenantID, id)
}
// PublishCourse publishes a course and notifies lecturer + enrolled members
// (发布与通知:生成签到码由排课动作触发,这里发站内通知流水)。
func (s *trainingService) PublishCourse(ctx context.Context, tenantID uint64, id, updaterID string) (*types.TrainingCourse, error) {
course, err := s.GetCourse(ctx, tenantID, id)
if err != nil {
return nil, err
}
if course.Status == types.TrainingCoursePublished {
return course, nil
}
// 发布必填校验(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
}
hasLibCourseware := strings.TrimSpace(lib.MaterialName) != "" ||
strings.TrimSpace(lib.FileKey) != "" ||
strings.TrimSpace(lib.KnowledgeID) != ""
if len(materials) == 0 && !hasLibCourseware {
return nil, errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)")
}
}
// 参加人员(2026-11 需求收紧:发布时校验参加人员不能为空):场次学员名单
// 有人(跨场次)即已设置;否则 post_scope 姓名须至少一人匹配到员工名册 ——
// 需求确认同步的 post_scope 是「适合人员」部门名串(匹配不到任何员工),
// 不能视为已设置,防止名单为空的计划带空应培名单发布。
enrolled, enrolledErr := s.repo.CountEnrolledMembersByCourseID(ctx, tenantID, course.ID)
if enrolledErr != nil {
return nil, enrolledErr
}
if enrolled == 0 && !s.postScopeHasMember(ctx, tenantID, course.PostScope) {
return nil, errors.NewBadRequestError("发布前需先设置参加人员").
WithDetails("参加人员不能为空;可在月培训计划「调整」中确认(默认为所属部门下的人员)后保存再发布")
}
if course.Mode != types.TrainingCourseModeOnline {
// 授课时间/地点与列表展示同口径(场次排期优先,2026-11-26 复测修复):
// 列表「授课时间/地点」列在课程级字段为空时展示场次排期值,校验若只读
// 课程级字段会把「场次已排期的存量草稿」误报为未设置 —— 课程级字段为空
// 时以最靠前的有效场次兜底(仅用于校验,不回写)。
if strings.TrimSpace(course.TeachTime) == "" || strings.TrimSpace(course.Location) == "" {
if session, sessErr := s.repo.FirstCourseSession(ctx, tenantID, course.ID); sessErr == nil && session != nil {
if strings.TrimSpace(course.TeachTime) == "" && session.StartAt != nil {
course.TeachTime = session.StartAt.Format("2006-01-02 15:04")
}
if strings.TrimSpace(course.Location) == "" {
course.Location = session.Location
}
}
}
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
if err := s.repo.UpdateCourse(ctx, course); err != nil {
return nil, err
}
// 线上课:发布即按部门范围批量生成学习任务并通知(必修推送)。
if course.Mode == types.TrainingCourseModeOnline {
s.publishOnlineLearningTasks(ctx, tenantID, course, updaterID)
}
// 通知讲师。
if course.LecturerID != "" {
lecturer, err := s.repo.GetMember(ctx, tenantID, course.LecturerID)
if err == nil && lecturer != nil {
_ = s.Notify(ctx, tenantID, lecturer.UserID, "course_publish",
"课程发布提醒", fmt.Sprintf("您授课的课程《%s》已发布,请查看课表安排。", course.Name),
"course", course.ID)
}
}
logger.Infof(ctx, "[Training] course published, tenant=%d course=%s operator=%s", tenantID, id, updaterID)
return course, nil
}
// postScopeHasMember post_scope 姓名串(、/,/,/;/;/空格分隔)至少一人匹配到员工
// 名册(姓名或工号)即认为已设置参加人员(2026-11 需求:需求确认同步的 post_scope
// 是「适合人员」部门名串,匹配不到任何员工,不算已设置)。名册查询失败时返回
// false,交由上层按「未设置参加人员」统一拦截,不放行空名单。
func (s *trainingService) postScopeHasMember(ctx context.Context, tenantID uint64, postScope string) bool {
names := map[string]struct{}{}
for _, part := range strings.FieldsFunc(postScope, func(r rune) bool {
return r == '、' || r == ',' || r == ',' || r == ';' || r == ';' || r == ' ' || r == '\t'
}) {
if part = strings.TrimSpace(part); part != "" {
names[part] = struct{}{}
}
}
if len(names) == 0 {
return false
}
if s.org == nil {
return false
}
members, _, err := s.org.ListEmployees(ctx, tenantID, types.OrgModuleTraining, &types.OrgListQuery{Page: 1, PageSize: 2000})
if err != nil {
logger.Error(ctx, "Failed to list members for publish participant check", err)
return false
}
for _, m := range members {
if m == nil {
continue
}
if _, ok := names[m.UserName]; ok {
return true
}
if m.EmployeeNo != "" {
if _, ok := names[m.EmployeeNo]; ok {
return true
}
}
}
return false
}
// ListSessions returns sessions.
func (s *trainingService) ListSessions(ctx context.Context, tenantID uint64, q *interfaces.TrainingListQuery) ([]*types.TrainingCourseSession, error) {
return s.repo.ListSessions(ctx, tenantID, q)
}
// GetSession returns one session.
func (s *trainingService) GetSession(ctx context.Context, tenantID uint64, id string) (*types.TrainingCourseSession, error) {
session, err := s.repo.GetSession(ctx, tenantID, id)
if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
return session, nil
}
// ListEnrollmentsForSession exposes the roster read path.
func (s *trainingService) ListEnrollmentsForSession(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingEnrollment, error) {
return s.repo.ListEnrollments(ctx, tenantID, sessionID)
}
// SaveSession creates or updates a session; on create it notifies the lecturer
// and roster members (学员开课通知走 session_notice_student 单通道,站内+企微同推)。
func (s *trainingService) SaveSession(ctx context.Context, tenantID uint64, session *types.TrainingCourseSession, updaterID string) (*types.TrainingCourseSession, error) {
if session.CourseID == "" {
return nil, errors.NewBadRequestError("缺少课程")
}
if _, err := s.repo.GetCourse(ctx, tenantID, session.CourseID); err != nil {
return nil, errors.NewBadRequestError("课程不存在")
}
if session.Status == "" {
session.Status = types.TrainingSessionScheduled
}
// [2026-11 推学员] 通知方式归一化:空值(月度排期自动生成等入口)默认立即推,
// 非法值回退 immediate,保证调度器分支判断始终有确定语义。
if session.NotifyMode != types.TrainingNotifyModeDayBefore {
session.NotifyMode = types.TrainingNotifyModeImmediate
}
if session.StartAt != nil {
y, m, _ := session.StartAt.In(time.Local).Date()
session.Year, session.Month = y, int(m)
}
isCreate := session.ID == ""
if isCreate {
session.ID = trainingNewID()
session.TenantID = tenantID
if err := s.repo.CreateSession(ctx, session); err != nil {
return nil, err
}
} else {
session.TenantID = tenantID
if err := s.repo.UpdateSession(ctx, session); err != nil {
return nil, err
}
// 授课时间联动计划排期:场次带排期关联时,同步月度排期开始时间(fail-open)。
if session.MonthPlanID != "" && session.StartAt != nil {
if plan, planErr := s.repo.GetMonthPlan(ctx, tenantID, session.MonthPlanID); planErr == nil && plan != nil {
if plan.StartAt == nil || !plan.StartAt.Equal(*session.StartAt) {
_ = s.repo.UpdateMonthPlanStartAt(ctx, tenantID, plan.ID, session.StartAt)
}
}
}
}
// 变更自动同步:创建/改期后通知讲师(通知流水)。
if lecturer, err := s.repo.GetMember(ctx, tenantID, session.LecturerID); err == nil && lecturer != nil {
_ = s.Notify(ctx, tenantID, lecturer.UserID, "session_change",
"授课安排提醒", fmt.Sprintf("课程场次已更新:%s。", sessionTimeText(session)), "session", session.ID)
}
// [2026-11 推学员] 创建场次时名单学员同样走 session_notice_student 单通道:
// 站内+企微同推(文案走配置中心「提醒推送文案」模板,幂等防重)。正常入口
// 名单由 SetEnrollments 保存后通知,此处兜底创建即带名单的场景。
if isCreate && session.Status != types.TrainingSessionCancelled {
if targets, err := s.sessionNoticeTargets(ctx, tenantID, session.ID); err == nil && len(targets) > 0 {
if _, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID)); err != nil {
logger.Warnf(ctx, "[TrainingNotify] session %s create notices: %v", session.ID, err)
}
}
}
_ = updaterID
return session, nil
}
// sessionTimeText renders the session schedule for notifications.
func sessionTimeText(session *types.TrainingCourseSession) string {
if session.StartAt == nil {
return "待定"
}
return session.StartAt.In(time.Local).Format("2006-01-02 15:04")
}
// sessionCourseTitle resolves the course name for message texts.
func sessionCourseTitle(ctx context.Context, s *trainingService, tenantID uint64, session *types.TrainingCourseSession) string {
if course, err := s.repo.GetCourse(ctx, tenantID, session.CourseID); err == nil {
return course.Name
}
return "培训课程"
}
// SetEnrollments replaces the roster (按部门/岗位/名单批量选人)。
func (s *trainingService) SetEnrollments(ctx context.Context, tenantID uint64, sessionID string, memberIDs []string) ([]*types.TrainingEnrollment, error) {
if _, err := s.repo.GetSession(ctx, tenantID, sessionID); err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
enrollments := make([]*types.TrainingEnrollment, 0, len(memberIDs))
seen := map[string]struct{}{}
for _, mid := range memberIDs {
if mid == "" {
continue
}
if _, dup := seen[mid]; dup {
continue // 自动去重
}
seen[mid] = struct{}{}
enrollments = append(enrollments, &types.TrainingEnrollment{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: sessionID,
MemberID: mid,
Status: types.TrainingEnrollEnrolled,
})
}
if err := s.repo.ReplaceEnrollments(ctx, tenantID, sessionID, enrollments); err != nil {
return nil, err
}
// [2026-11 推学员] 名单学员通知收敛 session_notice_student 单通道:站内+
// 企微同推(文案走配置中心「提醒推送文案」模板:诚邀您参加「{course}」…),
// scene+唯一索引幂等 —— 重复保存/已通知学员不重发。替代旧"您被列入课程名单"
// 纯站内流水(push_status 为空,企微外箱永不消费 → 学员只收站内不推企微)。
if session, err := s.repo.GetSession(ctx, tenantID, sessionID); err == nil && session != nil &&
session.Status != types.TrainingSessionCancelled {
if targets, err := s.sessionNoticeTargets(ctx, tenantID, sessionID); err == nil && len(targets) > 0 {
if _, err := s.enqueueSessionNotices(ctx, tenantID, session, targets, s.loadPushEnabled(ctx, tenantID)); err != nil {
logger.Warnf(ctx, "[TrainingNotify] session %s enrollment notices: %v", sessionID, err)
}
}
}
return s.repo.ListEnrollments(ctx, tenantID, sessionID)
}
// SetEnrollmentResult marks one member completed/absent with a reason
// (未完成归因:课长/人事确认)。
func (s *trainingService) SetEnrollmentResult(ctx context.Context, tenantID uint64, enrollmentID, status, reason, operatorID string) (*types.TrainingEnrollment, error) {
switch status {
case types.TrainingEnrollCompleted, types.TrainingEnrollAbsent, types.TrainingEnrollEnrolled:
default:
return nil, errors.NewBadRequestError("状态不合法")
}
enrollment, err := s.repo.GetEnrollment(ctx, tenantID, enrollmentID)
if err != nil {
return nil, errors.NewNotFoundError("报名记录不存在")
}
enrollment.Status = status
enrollment.Reason = reason
enrollment.ConfirmedBy = operatorID
if status == types.TrainingEnrollCompleted {
now := time.Now()
enrollment.CompletedAt = &now
} else {
enrollment.CompletedAt = nil
}
if err := s.repo.UpdateEnrollment(ctx, enrollment); err != nil {
return nil, err
}
return enrollment, nil
}
// CreateMaterial records one material (文件本体由文件服务/知识库管理)。
func (s *trainingService) CreateMaterial(ctx context.Context, tenantID uint64, material *types.TrainingMaterial, updaterID string) (*types.TrainingMaterial, error) {
material.ID = trainingNewID()
material.TenantID = tenantID
material.UploaderID = updaterID
if err := s.repo.CreateMaterial(ctx, material); err != nil {
return nil, err
}
// [2026-11 推学员] 课件就绪后的补推钩子:immediate 场次补推未通知学员,
// day_before 场次若已进入 T-1 窗口同样补推(scene 幂等,不重发)。
// fail-open:补推失败不影响课件上传结果。
s.AfterMaterialUploaded(ctx, tenantID, material.CourseID)
return material, nil
}
// ListMaterials returns course materials.
// 计划未自带课件时回退关联课程的课程管理课件(000156 随课程带出,发布校验同口径):
// 以课程管理条目 id 作为虚拟课件 id 返回,学习详情页预览/文件流/进度上报同链路可用
// (GetMaterialFile 对虚拟 id 回退课程管理文件流);仅登记名称而无文件/知识库文档时
// 不合成(无内容可打开)。
func (s *trainingService) ListMaterials(ctx context.Context, tenantID uint64, courseID string) ([]*types.TrainingMaterial, error) {
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 指向课程,
// 与导入侧「关联课程 ID」形成双向绑定。
func (s *trainingService) AttachQuestionBank(ctx context.Context, tenantID uint64, courseID, bankID, updaterID string) error {
if bankID == "" {
return nil
}
bank, err := s.repo.GetQuestionBank(ctx, tenantID, bankID)
if err != nil {
return errors.NewNotFoundError("关联题库不存在")
}
if bank == nil {
return errors.NewNotFoundError("关联题库不存在")
}
return s.repo.UpdateQuestionBankCourse(ctx, tenantID, bankID, courseID)
}
// ---------------------------------------------------------------------------
// 签到域
// ---------------------------------------------------------------------------
// CreateSignCode generates (or refreshes) the session's sign-in code with an
// optional geo-fence; default expiry = start + 4h or now + 12h.
// 2026-11 轮换需求:每轮 token 有效期 = min(now + rotation_sec, 场次总有效期),
// 讲师页轮询 GetSignCode 惰性续轮。
func (s *trainingService) CreateSignCode(ctx context.Context, tenantID uint64, sessionID string, lat, lng float64, radius int, operatorID string) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, sessionID)
if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
// 半径兜底仅在真实圆心下生效:前端生成签到码不携带定位(圆心为零值)时
// 不启用围栏 —— 否则 (0,0)+300m 会把所有真实扫码判成定位异常(距离一万
// 公里级)。需要围栏时由生成方显式传 geo_lat/geo_lng。
if lat == 0 && lng == 0 {
radius = 0
} else if radius <= 0 {
radius = int(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "geo_radius_m", 300))
}
now := time.Now()
expire := now.Add(12 * time.Hour)
if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
expire = candidate
}
}
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation > 0 {
if capped := now.Add(rotation); capped.Before(expire) {
expire = capped
}
}
code := &types.TrainingSignCode{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: sessionID,
Token: trainingNewToken(),
ExpireAt: &expire,
GeoLat: lat,
GeoLng: lng,
GeoRadius: radius,
CreatedBy: operatorID,
}
if err := s.repo.UpsertSignCode(ctx, code); err != nil {
return nil, err
}
return code, nil
}
// trainingNewToken 生成签到短码(token 形式,页面直接携带)。
func trainingNewToken() string {
return strings.ReplaceAll(trainingNewID(), "-", "")[:32]
}
// GetSignCode returns the session's active sign-in code. 超过轮换窗口
// (rotation_sec,默认 5 分钟)时惰性轮换:旧 token 挪入 prev(宽限期内仍可
// 签到),新码即时生效 —— 讲师页每 10s 轮询本接口即可驱动自动更新。
func (s *trainingService) GetSignCode(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeBySession(ctx, tenantID, sessionID)
if err != nil {
return nil, errors.NewNotFoundError("尚未生成签到码")
}
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
if rotation <= 0 || time.Now().Before(code.UpdatedAt.Add(rotation)) {
return code, nil
}
return s.rotateSignCode(ctx, tenantID, code)
}
// rotateSignCode 轮换场次签到码:生成新 token,旧 token/有效期挪入 prev 供
// 宽限签到(rotation_grace_sec,默认 30s,0 = 严格作废);upsert 覆盖唯一行后
// 旧 token 即刻退出当前码位(GetSignCodeByToken 不再命中,自然作废)。
// 新码有效期 = min(now + rotation_sec, 场次总有效期):后者沿用开课 +4h /
// 兜底 +12h 的既有口径,超期后不再续轮,交由现有过期校验拦截。
func (s *trainingService) rotateSignCode(ctx context.Context, tenantID uint64, code *types.TrainingSignCode) (*types.TrainingSignCode, error) {
session, err := s.repo.GetSession(ctx, tenantID, code.SessionID)
if err != nil {
return nil, errors.NewNotFoundError("课程场次不存在")
}
now := time.Now()
rotation := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_sec", 300)) * time.Second
expire := now.Add(rotation)
overall := now.Add(12 * time.Hour)
if session.StartAt != nil {
if candidate := session.StartAt.Add(4 * time.Hour); candidate.After(now) {
overall = candidate
}
}
if expire.After(overall) {
expire = overall
}
next := &types.TrainingSignCode{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: code.SessionID,
Token: trainingNewToken(),
ExpireAt: &expire,
PrevToken: code.Token,
PrevExpireAt: code.ExpireAt,
GeoLat: code.GeoLat,
GeoLng: code.GeoLng,
GeoRadius: code.GeoRadius,
CreatedBy: code.CreatedBy,
}
if err := s.repo.UpsertSignCode(ctx, next); err != nil {
return nil, err
}
return next, nil
}
// Checkin performs the scan sign-in with rule-based anti-fraud checks:
// token/expiry, same-day, employee-no match, nonce replay,
// duplicate scan, late arrival, geo fence.
// 一期为确定性规则引擎,不调 LLM;规则参数来自 sign_policy 配置。
// 2026-11 企微扫码需求增强:
// - 培训当天校验:非当天扫码签到直接友好提示(提前扫/过期补扫分文案);
// - 工号严格校验(in.EmployeeNo 非空时):须与登录账号档案工号一致;
// - nonce 防重放 + client_ts 时钟偏差校验;
// - 轮换宽限:token 未命中当前码时接受 prev_token 在宽限期内签到。
// 2026-11-28 签到规则调整:签到不再限定发布培训计划时所选「参加人员」——
// 员工档案(org_employees)全员均可凭工号签到;是否要求培训人员不再拦截/进
// 异常待复核,由签到明细按名册实时标注(ListSignRecords 联查 in_roster)。
func (s *trainingService) Checkin(ctx context.Context, tenantID uint64, userID string, in *types.CheckinInput) (*types.TrainingSignRecord, error) {
if in == nil || in.Token == "" {
return nil, errors.NewBadRequestError("签到码无效")
}
token, lat, lng := in.Token, in.Lat, in.Lng
code, err := s.repo.GetSignCodeByToken(ctx, tenantID, token)
if err != nil {
// 轮换宽限:未命中当前码时尝试前码(prev_token),宽限期内放行。
code, err = s.resolveCheckinPrevToken(ctx, tenantID, token)
if err != nil {
return nil, errors.NewBadRequestError("签到码无效或已更新,请重新扫码")
}
}
if code.ExpireAt != nil && time.Now().After(*code.ExpireAt) {
return nil, errors.NewBadRequestError("签到码已过期")
}
session, err := s.repo.GetSession(ctx, tenantID, code.SessionID)
if err != nil {
return nil, errors.NewBadRequestError("课程场次不存在")
}
if session.Status == types.TrainingSessionCancelled || session.Status == types.TrainingSessionFinished {
return nil, errors.NewBadRequestError("该场次不在可签到状态")
}
member, err := s.repo.GetMemberByUserID(ctx, tenantID, userID)
if err != nil {
return nil, errors.NewForbiddenError("未建立培训档案,无法签到")
}
now := time.Now()
// 严格扫码链路(employee_no 非空,即 2026-11 新签到页):当天校验/工号一致
// 校验/nonce 防重放/时钟偏差仅作用于此链路。既有路径(登录态直签、代录补签)
// 行为不变 —— 尤其代录补签常发生在非当天,当天校验不得拦截。
strictScan := strings.TrimSpace(in.EmployeeNo) != ""
// 培训当天校验(2026-11 需求规则 1):非当天扫码签到,分提前/滞后友好提示。
// 时区固定北京时间,与前端 fmtBeijingTime 口径一致。
if strictScan && s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "same_day_check", 1) > 0 &&
session.StartAt != nil && !sameBeijingDay(now, *session.StartAt) {
if session.StartAt.After(now) {
return nil, errors.NewBadRequestError(
"培训尚未开始:该课程 " + fmtBeijingCST(session.StartAt) + " 开课,培训当天再来签到")
}
return nil, errors.NewBadRequestError("本课程签到已结束,无法补签")
}
// 工号严格校验(2026-11 需求规则 2):工号须与档案一致。2026-11-28 规则调整
// 后不再要求在「参加人员」名单中,名单外人员照常签到,由明细标注区分。
if strictScan {
if !strings.EqualFold(strings.TrimSpace(member.EmployeeNo), strings.TrimSpace(in.EmployeeNo)) {
return nil, errors.NewForbiddenError("录入工号与当前账号的档案工号不一致,请确认后重试")
}
}
// nonce 防重放 + 时钟偏差(仅扫码链路携带;同 nonce 二次提交直接拒绝)。
if strictScan && in.Nonce != "" {
if dup, derr := s.repo.GetSignRecordByNonce(ctx, tenantID, in.Nonce); derr == nil && dup != nil {
return nil, errors.NewBadRequestError("签到请求无效,请刷新页面后重试")
}
}
skewSec := s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "clock_skew_sec", 60)
if strictScan && in.ClientTS > 0 && skewSec > 0 {
if diff := now.UnixMilli() - in.ClientTS; diff > int64(skewSec)*1000 || diff < -int64(skewSec)*1000 {
return nil, errors.NewBadRequestError("签到请求时间异常,请校准手机时间后重试")
}
}
flags := []string{}
status := types.TrainingSignNormal
// 迟到判定。
lateAfterMin := s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "late_after_min", 15)
if session.StartAt != nil && now.After(session.StartAt.Add(time.Duration(lateAfterMin)*time.Minute)) {
flags = append(flags, "late")
status = types.TrainingSignLate
}
// 定位围栏判定。圆心 (0,0) 视为未配置(生成签到码不带定位时圆心落零值):
// 距离按 0 记、不打 outside —— 否则圆心在几万公里外,全国任意扫码全是定位异常。
distance := 0.0
if code.GeoRadius > 0 && (code.GeoLat != 0 || code.GeoLng != 0) {
distance = haversineMeters(lat, lng, code.GeoLat, code.GeoLng)
if distance > float64(code.GeoRadius) {
flags = append(flags, "outside")
status = types.TrainingSignOutside
}
}
// 重复扫码直接拒绝(唯一约束兜底)。
if _, err := s.repo.GetSignRecord(ctx, tenantID, session.ID, member.ID); err == nil {
return nil, errors.NewBadRequestError("您已签到,请勿重复扫码")
}
channel := in.Channel
if channel == "" {
channel = "wecom_scan"
}
flagsJSON := trainingJSONFromSlice(flags)
record := &types.TrainingSignRecord{
ID: trainingNewID(),
TenantID: tenantID,
SessionID: session.ID,
MemberID: member.ID,
SignedAt: now,
Channel: channel,
Lat: lat,
Lng: lng,
DistanceM: distance,
Status: status,
Nonce: strings.TrimSpace(in.Nonce),
AbnormalFlags: flagsJSON,
}
if err := s.repo.UpsertSignRecord(ctx, record); err != nil {
return nil, err
}
return record, nil
}
// resolveCheckinPrevToken 轮换宽限:当前码未命中时按前码定位,宽限期内放行
// (rotation_grace_sec,默认 30s,0 = 严格作废)。跨租户 token 一律拒绝。
func (s *trainingService) resolveCheckinPrevToken(ctx context.Context, tenantID uint64, token string) (*types.TrainingSignCode, error) {
code, err := s.repo.GetSignCodeByTokenGlobal(ctx, token)
if err != nil || code == nil || code.TenantID != tenantID || code.Token == token {
return nil, errors.NewBadRequestError("签到码无效")
}
grace := time.Duration(s.ruleFloat(ctx, tenantID, types.RuleKeySignPolicy, "rotation_grace_sec", 30)) * time.Second
if code.PrevExpireAt == nil || time.Now().After(code.PrevExpireAt.Add(grace)) {
return nil, errors.NewBadRequestError("签到码已更新,请重新扫码")
}
return code, nil
}
// fmtBeijingCST 时间格式化为北京时间文案(当天性提示用)。
func fmtBeijingCST(t *time.Time) string {
if t == nil {
return ""
}
return t.In(time.FixedZone("CST", 8*3600)).Format("2006-01-02 15:04")
}
// haversineMeters computes the great-circle distance in meters.
func haversineMeters(lat1, lng1, lat2, lng2 float64) float64 {
const earthRadius = 6371000.0
rad := math.Pi / 180
dLat := (lat2 - lat1) * rad
dLng := (lng2 - lng1) * rad
a := math.Sin(dLat/2)*math.Sin(dLat/2) +
math.Cos(lat1*rad)*math.Cos(lat2*rad)*math.Sin(dLng/2)*math.Sin(dLng/2)
return 2 * earthRadius * math.Asin(math.Min(1, math.Sqrt(a)))
}
// ListSignRecords returns the session's records joined with member info.
func (s *trainingService) ListSignRecords(ctx context.Context, tenantID uint64, sessionID string) ([]*types.TrainingSignRecord, error) {
return s.repo.ListSignRecords(ctx, tenantID, sessionID)
}
// ReviewSignRecord resolves an abnormal record: confirm → normal.
func (s *trainingService) ReviewSignRecord(ctx context.Context, tenantID uint64, recordID, decision, operatorID string) (*types.TrainingSignRecord, error) {
target, err := s.repo.GetSignRecordByID(ctx, tenantID, recordID)
if err != nil {
return nil, errors.NewNotFoundError("签到记录不存在")
}
now := time.Now()
if decision == "confirm" {
target.Status = types.TrainingSignNormal
} else {
target.Status = types.TrainingSignAbnormal
}
target.ReviewedBy = operatorID
target.ReviewedAt = &now
if err := s.repo.ReviewSignRecord(ctx, target); err != nil {
return nil, err
}
return target, nil
}
// SignSummary returns the session's sign statistics.
func (s *trainingService) SignSummary(ctx context.Context, tenantID uint64, sessionID string) (*types.TrainingSignSummary, error) {
return s.repo.SignSummary(ctx, tenantID, sessionID)
}
// ExportEvidence builds the 请款佐证包 xlsx (签到+成绩+时长+讲师 三件套)。
func (s *trainingService) ExportEvidence(ctx context.Context, tenantID uint64, sessionIDs []string) (string, []byte, error) {
if len(sessionIDs) == 0 {
return "", nil, errors.NewBadRequestError("请选择要导出的课程场次")
}
rows, err := s.repo.EvidenceRows(ctx, tenantID, sessionIDs)
if err != nil {
return "", nil, err
}
f := excelize.NewFile()
sheet := "佐证包"
f.SetSheetName("Sheet1", sheet)
// 2026-11-28 签到规则调整配套:全员可签到,佐证包标注要求/非要求培训人员。
headers := []string{"部门", "工号", "姓名", "签到时间", "讲师姓名", "课程名称", "上课时间", "学员考试成绩", "人员类型"}
for i, h := range headers {
cell, _ := excelize.CoordinatesToCellName(i+1, 1)
_ = f.SetCellValue(sheet, cell, h)
}
for r, row := range rows {
rosterLabel := "非要求培训人员"
if row.InRoster {
rosterLabel = "要求培训人员"
}
// 2026-11 需求:部门列剥离企微同步残留的「e10-<ID>」字样
values := []string{utils.CleanDeptName(row.DeptName), row.EmployeeNo, row.MemberName, row.SignedAt,
row.LecturerName, row.CourseName, row.SessionTime, row.ExamScore, rosterLabel}
for i, v := range values {
cell, _ := excelize.CoordinatesToCellName(i+1, r+2)
_ = f.SetCellValue(sheet, cell, v)
}
}
buf, err := f.WriteToBuffer()
if err != nil {
return "", nil, err
}
filename := fmt.Sprintf("training_evidence_%s.xlsx", time.Now().Format("20060102150405"))
logger.Infof(ctx, "[Training] evidence exported, tenant=%d sessions=%d rows=%d", tenantID, len(sessionIDs), len(rows))
return filename, buf.Bytes(), nil
}