Files
ai_academy/internal/handler/training/training.go
T
runny 4e25fce9aa feat(training): 企业培训迭代:推送深链接与签名下载、课程管理修复与收集模板调整
推送域(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 的头文件包含路径
2026-11-19 17:10:12 +08:00

1809 lines
66 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 training
import (
"context"
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"academy/internal/errors"
"academy/internal/filetransport"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
"academy/internal/utils"
"github.com/gin-gonic/gin"
)
// Handler 培训模块 HTTP 处理器。权限模型:
// - 路由层先过空间 RBAC(Viewer 及以上可访问学员功能,Contributor 及以上管理);
// - 本层再按培训模块角色(org_module_members, module_key='training')做业务角色细控(见 requireRoles)。
type Handler struct {
svc interfaces.TrainingService
// pusher 企微推送测试能力(由 training scheduler 提供,见 training_scheduler.go)。
pusher interfaces.TrainingNotificationPusher
}
// NewHandler constructs the training handler.
func NewHandler(svc interfaces.TrainingService, pusher interfaces.TrainingNotificationPusher) *Handler {
return &Handler{svc: svc, pusher: pusher}
}
// ---------------------------------------------------------------------------
// 请求上下文辅助
// ---------------------------------------------------------------------------
// callerTenantID reads the tenant id injected by the auth middleware.
func callerTenantID(c *gin.Context) uint64 {
return c.GetUint64(types.TenantIDContextKey.String())
}
// callerUserID reads the platform user id injected by the auth middleware.
func callerUserID(c *gin.Context) string {
v, _ := c.Get(types.UserIDContextKey.String())
s, _ := v.(string)
return s
}
// listQueryFromRequest parses the common list filters from the request.
func listQueryFromRequest(c *gin.Context) *interfaces.TrainingListQuery {
q := &interfaces.TrainingListQuery{
DeptID: c.Query("dept_id"),
Status: c.Query("status"),
CheckStatus: c.Query("check_status"),
Keyword: c.Query("keyword"),
Scope: c.Query("scope"),
}
if v, err := strconv.Atoi(c.Query("year")); err == nil {
q.Year = v
}
if v, err := strconv.Atoi(c.Query("month")); err == nil {
q.Month = v
}
if v, err := strconv.Atoi(c.Query("page")); err == nil {
q.Page = v
}
if v, err := strconv.Atoi(c.Query("page_size")); err == nil {
q.PageSize = v
}
return q
}
// requireRoles asserts the caller carries at least one of the given training
// roles. Workspace Admin/Owner (and SystemAdmin) bypass by design — this
// bootstraps the very first hr/clerk assignment before any employee row
// exists, and keeps tenant administrators in charge of the training module.
func (h *Handler) requireRoles(c *gin.Context, allowed ...string) (ok bool) {
tenantID := callerTenantID(c)
userID := callerUserID(c)
if tenantID == 0 || userID == "" {
_ = c.Error(errors.NewUnauthorizedError("未认证"))
return false
}
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
return true
}
member, err := h.svc.CurrentMember(c.Request.Context(), tenantID, userID)
if err != nil {
_ = c.Error(err)
return false
}
roles := member.TrainingRoleList()
// 角色按字典的权限分配传递展开后比对(自定义职称角色由此获得真实权限)。
roles = h.svc.ExpandTrainingRoles(c.Request.Context(), tenantID, roles)
for _, want := range allowed {
for _, has := range roles {
if want == has {
return true
}
}
}
// 报错文案用字典展示名(自定义/改名后的角色对用户可见的是 label)。
labels := types.RoleDictLabels(h.svc.RoleDict(c.Request.Context(), tenantID))
labelParts := make([]string, 0, len(allowed))
for _, want := range allowed {
if label := labels[want]; label != "" {
labelParts = append(labelParts, label)
} else {
labelParts = append(labelParts, want)
}
}
_ = c.Error(errors.NewForbiddenError("无权执行该操作,需要职称角色: " + strings.Join(labelParts, "/")))
return false
}
// ---------------------------------------------------------------------------
// 数据范围:课程/计划类列表按调用方职称角色收窄(权限模型 §数据范围)
// ---------------------------------------------------------------------------
// dataScope 调用方数据范围。
type dataScope int
const (
// scopeManager 全局视角:人事/课长/经理(含自定义角色继承)与空间管理员。
scopeManager dataScope = iota
// scopeLecturer 纯讲师:仅自己讲师相关的课程/场次(维护视角);
// 学员目录视图(scope=student)下仍看全部已发布课程(讲师默认也是学员)。
scopeLecturer
// scopeTrainee 纯学员:仅已发布课程(学员为全员隐式默认角色)。
scopeTrainee
)
// callerDataScope 判定调用方数据范围;取不到档案时兜底纯学员(与隐式 trainee
// 口径一致),只读列表不阻断。
func (h *Handler) callerDataScope(c *gin.Context) (dataScope, *types.TrainingMember) {
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
return scopeManager, nil
}
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil {
return scopeTrainee, nil
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
switch {
case types.HasTrainingRole(roles, types.TrainingRoleHR),
types.HasTrainingRole(roles, types.TrainingRoleSupervisor),
types.HasTrainingRole(roles, types.TrainingRoleManager):
return scopeManager, member
case types.HasTrainingRole(roles, types.TrainingRoleLecturer):
return scopeLecturer, member
default:
return scopeTrainee, member
}
}
// callerDeptScope 计划类列表的部门范围限定:人事/空间管理员为全局视角(返回
// 空串不限定);经理/课长(含继承课长的自定义角色)只能查询本部门数据,返回其
// 所在部门 ID;其余角色(讲师/学员)不限定(本就无管理入口)。
func (h *Handler) callerDeptScope(c *gin.Context) string {
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
return ""
}
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil || member == nil {
return ""
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
// 人事全量;经理继承课长权限组,与课长一致收窄本部门
if types.HasTrainingRole(roles, types.TrainingRoleHR) {
return ""
}
if types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
return member.DeptID
}
return ""
}
// checkCourseVisibility 课程详情可见性:全局视角与已发布课程对所有人开放;
// 纯讲师另可见自己相关的未发布课程(供维护);纯学员不可见未发布课程。
func (h *Handler) checkCourseVisibility(c *gin.Context, course *types.TrainingCourse) error {
if course == nil {
return nil
}
scope, _ := h.callerDataScope(c)
if scope == scopeManager || course.Status == types.TrainingCoursePublished {
return nil
}
if scope == scopeLecturer && course.LecturerID == callerUserID(c) {
return nil
}
return errors.NewForbiddenError("无权查看未发布课程")
}
// ---------------------------------------------------------------------------
// 组织与成员
// ---------------------------------------------------------------------------
// ListDepts GET /training/depts
func (h *Handler) ListDepts(c *gin.Context) {
depts, err := h.svc.ListDepts(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": depts})
}
// saveDeptRequest is the body of POST /training/depts.
type saveDeptRequest struct {
ID string `json:"id"`
ParentID string `json:"parent_id"`
Name string `json:"name" binding:"required"`
Code string `json:"code"`
Sort int `json:"sort"`
}
// SaveDept POST /training/depts
func (h *Handler) SaveDept(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
return
}
var req saveDeptRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
dept, err := h.svc.SaveDept(ctx, callerTenantID(c), &types.TrainingDept{
ID: req.ID, ParentID: req.ParentID, Name: req.Name, Code: req.Code, Sort: req.Sort,
})
if err != nil {
logger.Error(ctx, "Failed to save training dept", err)
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": dept})
}
// DeleteDept DELETE /training/depts/:id
func (h *Handler) DeleteDept(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
return
}
if err := h.svc.DeleteDept(ctx, callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ListMembers GET /training/members
func (h *Handler) ListMembers(c *gin.Context) {
members, total, err := h.svc.ListMembers(c.Request.Context(), callerTenantID(c), listQueryFromRequest(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": members, "total": total}})
}
// importMemberItem is one row of the member import payload.
type importMemberItem struct {
UserID string `json:"user_id" binding:"required"`
EmployeeNo string `json:"employee_no"`
DeptID string `json:"dept_id"`
Post string `json:"post"`
Roles []string `json:"roles"`
LecturerRate float64 `json:"lecturer_rate"`
WecomUserid string `json:"wecom_userid"`
Status string `json:"status"`
}
// ImportMembersRequest is the body of POST /training/members/import.
type ImportMembersRequest struct {
Members []importMemberItem `json:"members" binding:"required,min=1"`
}
// ImportMembers POST /training/members/import
func (h *Handler) ImportMembers(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
return
}
var req ImportMembersRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
members := make([]*types.TrainingMember, 0, len(req.Members))
for _, item := range req.Members {
members = append(members, &types.TrainingMember{
UserID: item.UserID,
EmployeeNo: item.EmployeeNo,
DeptID: item.DeptID,
Post: item.Post,
Roles: rolesToJSON(item.Roles),
LecturerRate: item.LecturerRate,
WecomUserid: item.WecomUserid,
Status: item.Status,
})
}
count, err := h.svc.ImportMembers(ctx, callerTenantID(c), members, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": count}})
}
// UpdateMemberWecomUserid PUT /training/members/:id/wecom-userid — 维护成员的
// 企微 userid(培训提醒推送目标;空串=解绑)。
func (h *Handler) UpdateMemberWecomUserid(c *gin.Context) {
ctx := c.Request.Context()
// 经理与人事同权(000159):职称角色页对经理开放。
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
var req struct {
WecomUserid string `json:"wecom_userid"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
member, err := h.svc.UpdateMemberWecomUserid(ctx, callerTenantID(c), c.Param("id"), req.WecomUserid)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
}
// rolesToJSON encodes the roles slice into jsonb payload.
func rolesToJSON(roles []string) types.JSON {
if len(roles) == 0 {
roles = []string{types.TrainingRoleTrainee}
}
data, _ := jsonMarshal(roles)
return types.JSON(data)
}
// UpdateMemberRoles PUT /training/members/:id/roles — 经理与人事同权(000159)。
func (h *Handler) UpdateMemberRoles(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleManager) {
return
}
var req struct {
Roles []string `json:"roles" binding:"required,min=1"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
member, err := h.svc.UpdateMemberRoles(ctx, callerTenantID(c), c.Param("id"), req.Roles, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
}
// Me GET /training/members/me — 当前用户的培训档案(角色决定工作台)。
func (h *Handler) Me(c *gin.Context) {
ctx := c.Request.Context()
member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
}
// ---------------------------------------------------------------------------
// 计划域
// ---------------------------------------------------------------------------
// ListDemands GET /training/demands — 课长本部门口径:纯课长只能查询本部门需求。
func (h *Handler) ListDemands(c *gin.Context) {
q := listQueryFromRequest(c)
if dept := h.callerDeptScope(c); dept != "" {
q.DeptID = dept
}
items, total, err := h.svc.ListDemands(c.Request.Context(), callerTenantID(c), q)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
}
// ListDemandYears GET /training/demands/years — 需求库实际年份去重列表(降序),
// 年度需求收集页年份下拉数据源(前端默认选中最新一年);纯课长收窄本部门口径。
func (h *Handler) ListDemandYears(c *gin.Context) {
years, err := h.svc.ListDemandYears(c.Request.Context(), callerTenantID(c), h.callerDeptScope(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": years})
}
// saveDemandRequest is the body of POST /training/demands.
// 字段口径对齐「年度教育培训收集模板」(docs/moban):厂区/主办单位(→dept_id)/课程名称/
// 次数/参加人员(→post_scope)/地点/分类/培训讲师/月份。
type saveDemandRequest struct {
ID string `json:"id"`
Year int `json:"year"`
DeptID string `json:"dept_id"`
CourseName string `json:"course_name" binding:"required"`
Plant string `json:"plant"`
Category string `json:"category"`
SessionCount int `json:"session_count"`
Location string `json:"location"`
PostScope string `json:"post_scope"`
LecturerID string `json:"lecturer_id"`
// LecturerExternal 外部讲师姓名(非系统员工;lecturer_id 为空时生效)。
LecturerExternal string `json:"lecturer_external"`
// TrainType 内/外培训(内部/外部,选填;来自需求表模板「內/外培訓」列)。
TrainType string `json:"train_type"`
TargetCount int `json:"target_count"`
Hours float64 `json:"hours"`
ExpectMonth int `json:"expect_month"`
// PlannedTime 计划培训时间(YYYY-MM-DD HH:mm 或 YYYY-MM-DD,选填;确认后同步课程)。
PlannedTime string `json:"planned_time"`
Remark string `json:"remark"`
}
// callerCanMutateDemand 需求编辑/删除权限:培训管理角色(hr/clerk/supervisor)、
// 空间管理员或提报本人;未确认需求谁提报谁可改,已确认统一由人事回退。
func (h *Handler) callerCanMutateDemand(c *gin.Context, submitterID string) bool {
if uid := callerUserID(c); uid != "" && uid == submitterID {
return true
}
if callerRole := types.TenantRoleFromContext(c.Request.Context()); callerRole.IsValid() &&
(callerRole == types.TenantRoleAdmin || callerRole == types.TenantRoleOwner) {
return true
}
member, err := h.svc.CurrentMember(c.Request.Context(), callerTenantID(c), callerUserID(c))
if err != nil {
return false
}
roles := h.svc.ExpandTrainingRoles(c.Request.Context(), callerTenantID(c), member.TrainingRoleList())
return types.HasTrainingRole(roles, types.TrainingRoleHR) ||
types.HasTrainingRole(roles, types.TrainingRoleSupervisor)
}
// SaveDemand POST /training/demands — 主管在线提报/编辑未确认需求。
// 部门为必填口径:请求未带时按提报人所在部门(org_employees.dept_id)自动获取。
func (h *Handler) SaveDemand(c *gin.Context) {
ctx := c.Request.Context()
var req saveDemandRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
// 编辑校验:已确认不可改;非提报本人且无管理角色不可改。
var existing *types.TrainingDemand
if req.ID != "" {
var err error
existing, err = h.svc.GetDemand(ctx, callerTenantID(c), req.ID)
if err != nil {
_ = c.Error(err)
return
}
if existing.Status == types.TrainingDemandConfirmed {
_ = c.Error(errors.NewBadRequestError("已确认的需求不可编辑"))
return
}
if !h.callerCanMutateDemand(c, existing.SubmitterID) {
_ = c.Error(errors.NewForbiddenError("仅提报人或培训管理角色可编辑该需求"))
return
}
}
// 部门口径:新建未带时按提报人所在部门自动获取;编辑未显式指定时保留原部门。
deptID := trimSpace(req.DeptID)
if deptID == "" {
if existing != nil {
deptID = existing.DeptID
} else if member, err := h.svc.CurrentMember(ctx, callerTenantID(c), callerUserID(c)); err == nil {
deptID = member.DeptID
}
}
demand, err := h.svc.SaveDemand(ctx, callerTenantID(c), &types.TrainingDemand{
ID: req.ID, Year: req.Year, DeptID: deptID,
SubmitterID: callerUserID(c), CourseName: req.CourseName,
Plant: req.Plant, Category: req.Category, SessionCount: req.SessionCount,
Location: req.Location, PostScope: req.PostScope, LecturerID: req.LecturerID,
LecturerExternal: trimSpace(req.LecturerExternal), TrainType: trimSpace(req.TrainType),
TargetCount: req.TargetCount, Hours: req.Hours, ExpectMonth: req.ExpectMonth,
PlannedTime: trimSpace(req.PlannedTime), Remark: req.Remark,
})
if err != nil {
_ = c.Error(err)
return
}
// 需求讲师回写课程管理(000156):在线改选讲师后课程管理同步追加(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), []*types.TrainingDemand{demand})
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
}
// DeleteDemand DELETE /training/demands/:id — 删除未确认需求。
func (h *Handler) DeleteDemand(c *gin.Context) {
ctx := c.Request.Context()
demand, err := h.svc.GetDemand(ctx, callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if demand.Status == types.TrainingDemandConfirmed {
_ = c.Error(errors.NewBadRequestError("已确认的需求不可删除"))
return
}
if !h.callerCanMutateDemand(c, demand.SubmitterID) {
_ = c.Error(errors.NewForbiddenError("仅提报人或培训管理角色可删除该需求"))
return
}
if err := h.svc.DeleteDemand(ctx, callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ListLecturers GET /training/lecturers — 需求提报的讲师下拉数据源。
func (h *Handler) ListLecturers(c *gin.Context) {
items, err := h.svc.ListLecturers(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// ListPosts GET /training/posts — 需求提报的岗位下拉数据源(实际岗位)。
func (h *Handler) ListPosts(c *gin.Context) {
posts, err := h.svc.ListPosts(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": posts})
}
// ImportDemands POST /training/demands/import — 调研表在线化批量导入。
func (h *Handler) ImportDemands(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
Demands []saveDemandRequest `json:"demands" binding:"required,min=1"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
demands := make([]*types.TrainingDemand, 0, len(req.Demands))
for _, item := range req.Demands {
demands = append(demands, &types.TrainingDemand{
Year: item.Year, DeptID: item.DeptID, CourseName: item.CourseName,
Plant: item.Plant, Category: item.Category, SessionCount: item.SessionCount,
Location: item.Location, PostScope: item.PostScope, LecturerID: item.LecturerID,
LecturerExternal: trimSpace(item.LecturerExternal), TrainType: trimSpace(item.TrainType),
TargetCount: item.TargetCount, Hours: item.Hours, ExpectMonth: item.ExpectMonth,
PlannedTime: trimSpace(item.PlannedTime), Remark: item.Remark,
})
}
result, err := h.svc.ImportDemands(ctx, callerTenantID(c), demands, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
// 需求讲师回写课程管理(000156):改选讲师后课程管理同步追加该讲师(fail-open)。
h.syncDemandLecturerToLibrary(ctx, callerTenantID(c), callerUserID(c), demands)
// 导入后自动推送部门经理核验(000157,站内+企微,fail-open)。
notified := h.notifyDemandVerify(ctx, callerTenantID(c), demands)
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result), "notified": notified}})
}
// demandConfirmDenied 年度需求核验确认的统一拒绝文案(000154 权限收窄):
// 仅「需求归属部门」内、职称角色为经理的成员可确认,其余人员一律提示联系部门经理。
const demandConfirmDenied = "暂无权限,请联系部门经理~"
// ConfirmDemand POST /training/demands/:id/confirm — 经理核验确认(部门+角色双校验)。
// 仅「需求归属部门的成员且职称角色为经理」可核验(000154 收窄:人事/空间管理员/
// 其他部门经理一律拒绝),统一提示「暂无权限,请联系部门经理~」;
// 部门校验先于确认落库,避免越权时已改状态。
func (h *Handler) ConfirmDemand(c *gin.Context) {
ctx := c.Request.Context()
tenantID, userID := callerTenantID(c), callerUserID(c)
member, err := h.svc.CurrentMember(ctx, tenantID, userID)
if err != nil {
_ = c.Error(err)
return
}
if member == nil {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, member.TrainingRoleList())
if !types.HasTrainingRole(roles, types.TrainingRoleManager) {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
existing, err := h.svc.GetDemand(ctx, tenantID, c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
// 本部门口径:仅可核验本部门需求(部门缺失的需求先由人事/提报人补全部门)。
if existing.DeptID == "" || existing.DeptID != member.DeptID {
_ = c.Error(errors.NewForbiddenError(demandConfirmDenied))
return
}
demand, err := h.svc.ConfirmDemand(ctx, tenantID, c.Param("id"), userID)
if err != nil {
_ = c.Error(err)
return
}
// 已确认需求自动生成草稿课程到课程管理(fail-open,不阻断确认)。
h.syncDemandCourse(ctx, tenantID, demand, userID)
// 确认转月培训计划后自动推送讲师与部门课长维护(000157,站内+企微,fail-open)。
h.notifyDemandConfirmed(ctx, tenantID, userID, demand)
c.JSON(http.StatusOK, gin.H{"success": true, "data": demand})
}
// syncDemandCourse 已确认需求同步生成草稿课程(同名课程已存在则跳过,避免重复确认重复建课)。
func (h *Handler) syncDemandCourse(ctx context.Context, tenantID uint64, demand *types.TrainingDemand, updaterID string) {
if demand == nil || trimSpace(demand.CourseName) == "" {
return
}
courses, _, err := h.svc.ListCourses(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 200})
if err == nil {
for _, c := range courses {
if c != nil && c.Name == demand.CourseName {
return
}
}
}
category := trimSpace(demand.Category)
course := &types.TrainingCourse{
Name: demand.CourseName,
Mode: "offline",
Type: "required",
Hours: demand.Hours,
LecturerID: demand.LecturerID,
DeptIDs: sliceToJSON([]string{demand.DeptID}),
PostScope: demand.PostScope,
}
// 经理确认自动转月度计划(000153):回填来源需求 id 供列表/详情溯源;
// 课程管理存在同名课程时直接关联(计划侧自动带出并锁定课程信息),
// 无同名课程时课长在月度计划编辑弹窗手动选择课程管理课程。
course.SourceDemandID = demand.ID
if libItems, _, libErr := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500}); libErr == nil {
for _, item := range libItems {
if item != nil && item.Name == demand.CourseName {
course.LibraryCourseID = item.ID
break
}
}
}
// 授课时间默认取需求「期望月份」(YYYY-MM,课程管理侧可修改并留版本记录)。
if demand.Year > 0 && demand.ExpectMonth >= 1 && demand.ExpectMonth <= 12 {
course.TeachTime = fmt.Sprintf("%04d-%02d", demand.Year, demand.ExpectMonth)
}
// 计划培训月份:需求侧为「YYYY-M」(如 2027-1),归一为课程口径 YYYY-MM;
// 旧日期格式(YYYY-MM-DD 等)原样同步。
course.PlannedTime = demandPlannedMonthOf(trimSpace(demand.PlannedTime))
// 需求录入信息全量同步(000150 补充的课程侧落点),课程详情弹窗只读回显。
// 内/外培训、厂区、地点、培训次数、备注原样带入;外部讲师仅在无系统讲师时生效。
externalLecturer := trimSpace(demand.LecturerExternal)
if demand.LecturerID != "" {
externalLecturer = ""
}
course.TrainType = trimSpace(demand.TrainType)
course.Plant = trimSpace(demand.Plant)
course.Location = trimSpace(demand.Location)
course.SessionCount = demand.SessionCount
course.LecturerExternal = externalLecturer
course.Remark = trimSpace(demand.Remark)
if category != "" {
course.Tags = sliceToJSON([]string{category})
}
if _, err := h.svc.SaveCourse(ctx, tenantID, course, updaterID); err != nil {
logger.Error(ctx, "Failed to sync confirmed demand to draft course", err)
return
}
// 参加人员与场次学员名单合一:按姓名匹配在职员工,建默认场次并写入学员名单,
// 应到人数(跨场次名单去重)即由此统计;未匹配到的姓名(外部人员/笔误)跳过。
h.syncDemandParticipants(ctx, tenantID, course, demand, updaterID)
// 讲师自动授权:需求选定讲师(可能是任意员工)自动补齐 lecturer 角色绑定。
if err := h.svc.EnsureLecturerRole(ctx, tenantID, course.LecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role", err)
}
}
// syncDemandParticipants 需求参加人员 → 场次学员名单:拆分姓名、匹配员工档案,
// 为新同步课程建默认场次(计划培训时间/授课地点带入)并批量写入名单。
func (h *Handler) syncDemandParticipants(ctx context.Context, tenantID uint64, course *types.TrainingCourse, demand *types.TrainingDemand, updaterID string) {
participants := splitNames(demand.PostScope)
if len(participants) == 0 {
return
}
members, _, err := h.svc.ListMembers(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 2000})
if err != nil {
logger.Error(ctx, "Failed to list members for demand participants", err)
return
}
memberIDs := make([]string, 0, len(participants))
seen := map[string]bool{}
for _, p := range participants {
for _, m := range members {
if m != nil && m.UserName == p && !seen[m.ID] {
memberIDs = append(memberIDs, m.ID)
seen[m.ID] = true
}
}
}
if len(memberIDs) == 0 {
return
}
session := &types.TrainingCourseSession{
CourseID: course.ID,
Location: trimSpace(demand.Location),
LecturerID: demand.LecturerID,
NotifyMode: types.TrainingNotifyModeImmediate,
}
if startAt := parseFlexibleTime(demand.PlannedTime); startAt != nil {
session.StartAt = startAt
if demand.Hours > 0 {
end := startAt.Add(time.Duration(demand.Hours * float64(time.Hour)))
session.EndAt = &end
}
}
saved, err := h.svc.SaveSession(ctx, tenantID, session, updaterID)
if err != nil {
logger.Error(ctx, "Failed to create default session for demand participants", err)
return
}
if _, err := h.svc.SetEnrollments(ctx, tenantID, saved.ID, memberIDs); err != nil {
logger.Error(ctx, "Failed to enroll demand participants", err)
}
}
// splitNames 拆分参加人员姓名(、/,/,/;/空格分隔),去空去重保序。
func splitNames(raw string) []string {
fields := strings.FieldsFunc(raw, func(r rune) bool {
return r == '、' || r == ',' || r == ',' || r == ';' || r == ';' || r == ' ' || r == '\t'
})
out := make([]string, 0, len(fields))
seen := map[string]bool{}
for _, f := range fields {
f = trimSpace(f)
if f == "" || seen[f] {
continue
}
seen[f] = true
out = append(out, f)
}
return out
}
// trainingDeptRoleRecipients 取指定部门具有任一目标职称角色(按权限分配展开后)
// 的在职成员 user_id;部门为空或查询失败返回空(fail-open 供推送场景使用)。
func (h *Handler) trainingDeptRoleRecipients(ctx context.Context, tenantID uint64, deptID string, want ...types.TrainingRole) []string {
if deptID == "" {
return nil
}
members, _, err := h.svc.ListMembers(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil {
return nil
}
out := []string{}
for _, m := range members {
if m == nil || m.DeptID != deptID || m.UserID == "" {
continue
}
roles := h.svc.ExpandTrainingRoles(ctx, tenantID, m.TrainingRoleList())
for _, w := range want {
if types.HasTrainingRole(roles, w) {
out = append(out, m.UserID)
break
}
}
}
return out
}
// notifyDemandVerify 需求导入后自动推送(000157):按部门聚合,站内+企微通知
// 该部门经理(职称角色经理)进行核实【确认】;fail-open 不阻断导入。
// 返回成功送达的通知数(写入导入响应,前端提示)。
func (h *Handler) notifyDemandVerify(ctx context.Context, tenantID uint64, demands []*types.TrainingDemand) int {
byDept := map[string][]string{}
year := 0
for _, d := range demands {
if d == nil || d.DeptID == "" || trimSpace(d.CourseName) == "" {
continue
}
byDept[d.DeptID] = append(byDept[d.DeptID], trimSpace(d.CourseName))
if d.Year > 0 && year == 0 {
year = d.Year
}
}
if len(byDept) == 0 {
return 0
}
deptNames := map[string]string{}
if depts, err := h.svc.ListDepts(ctx, tenantID); err == nil {
for _, d := range depts {
if d != nil {
deptNames[d.ID] = d.Name
}
}
}
sent := 0
for deptID, courses := range byDept {
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, deptID, types.TrainingRoleManager)
if len(recipients) == 0 {
continue
}
name := deptNames[deptID]
if name == "" {
name = deptID
}
title := fmt.Sprintf("【年度培训需求核验】%d年度 %s 培训需求待核验", year, name)
content := fmt.Sprintf(
"%s 新导入 %d 条年度培训需求(课程:%s)。请登录 AIDO → 企业培训 → 年培训计划,逐条核验并【确认】,确认后将自动转入月培训计划。",
name, len(courses), strings.Join(courses, "、"),
)
n, err := h.svc.BroadcastNotification(ctx, tenantID, recipients, "demand_verify", title, content, "plan", strconv.Itoa(year), "")
if err != nil {
logger.Error(ctx, "Failed to notify dept managers for demand verify", err)
continue
}
sent += n
}
return sent
}
// notifyDemandConfirmed 需求确认转月培训计划后自动推送(000157):站内+企微通知
// 该课程讲师与部门课长维护培训相关信息(讲师维护课程信息,课长安排授课计划);
// 确认操作人自身不重复通知;fail-open 不阻断确认。
func (h *Handler) notifyDemandConfirmed(ctx context.Context, tenantID uint64, operatorID string, demand *types.TrainingDemand) {
if demand == nil {
return
}
recipients := h.trainingDeptRoleRecipients(ctx, tenantID, demand.DeptID, types.TrainingRoleSupervisor)
recipients = append(recipients, trimSpace(demand.LecturerID))
seen := map[string]bool{}
final := []string{}
for _, uid := range recipients {
if uid == "" || uid == operatorID || seen[uid] {
continue
}
seen[uid] = true
final = append(final, uid)
}
if len(final) == 0 {
return
}
title := fmt.Sprintf("【培训计划维护】%s 已确认转入月培训计划", demand.CourseName)
content := fmt.Sprintf(
"%d年度需求「%s」已核验确认并自动转入月培训计划:请讲师维护课程信息(课件/试题),课长安排授课时间/地点与学员名单。入口:AIDO → 企业培训 → 月培训计划。",
demand.Year, demand.CourseName,
)
if _, err := h.svc.BroadcastNotification(ctx, tenantID, final, "demand_confirmed", title, content, "course", demand.ID, ""); err != nil {
logger.Error(ctx, "Failed to notify lecturer and supervisors after demand confirm", err)
}
}
// syncDemandLecturerToLibrary 需求讲师回写课程管理(000156):需求(导入/在线保存)
// 按课程名称匹配课程管理条目,讲师与条目不一致时以需求讲师为准更新(改选讲师后
// 课程管理同步追加为该讲师);同批同名取首条。fail-open:失败仅记日志不阻断导入。
func (h *Handler) syncDemandLecturerToLibrary(ctx context.Context, tenantID uint64, updaterID string, demands []*types.TrainingDemand) {
byName := map[string]*types.TrainingDemand{}
for _, d := range demands {
if d == nil || trimSpace(d.CourseName) == "" {
continue
}
if trimSpace(d.LecturerID) == "" && trimSpace(d.LecturerExternal) == "" {
continue
}
if _, ok := byName[d.CourseName]; !ok {
byName[d.CourseName] = d
}
}
if len(byName) == 0 {
return
}
items, _, err := h.svc.ListCourseLibraryItems(ctx, tenantID, &interfaces.TrainingListQuery{Page: 1, PageSize: 500})
if err != nil {
logger.Error(ctx, "Failed to list course library for lecturer sync", err)
return
}
for _, item := range items {
if item == nil {
continue
}
d, ok := byName[item.Name]
if !ok {
continue
}
lecturerID, lecturerExt := trimSpace(d.LecturerID), trimSpace(d.LecturerExternal)
if item.LecturerID == lecturerID && item.LecturerExternal == lecturerExt {
continue
}
updated := *item
updated.LecturerID = lecturerID
updated.LecturerExternal = lecturerExt
if _, err := h.svc.SaveCourseLibraryItem(ctx, tenantID, &updated, updaterID); err != nil {
logger.Error(ctx, "Failed to sync demand lecturer to course library", err)
continue
}
// 系统员工讲师自动补齐讲师角色(讲师名册/下拉可见,fail-open)。
if err := h.svc.EnsureLecturerRole(ctx, tenantID, lecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role on demand sync", err)
}
}
}
// GenerateAnnualPlan POST /training/annual-plans/generate — AI 汇总生成年度排期。
func (h *Handler) GenerateAnnualPlan(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
return
}
var req struct {
Year int `json:"year"`
}
_ = c.ShouldBindJSON(&req)
plans, err := h.svc.GenerateAnnualPlan(ctx, callerTenantID(c), req.Year, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"generated": len(plans), "items": plans}})
}
// ListAnnualPlans GET /training/annual-plans — 课长本部门口径:纯课长仅本部门排期。
func (h *Handler) ListAnnualPlans(c *gin.Context) {
year, _ := strconv.Atoi(c.Query("year"))
plans, err := h.svc.ListAnnualPlans(c.Request.Context(), callerTenantID(c), year)
if err != nil {
_ = c.Error(err)
return
}
if dept := h.callerDeptScope(c); dept != "" {
scoped := make([]*types.TrainingAnnualPlan, 0, len(plans))
for _, p := range plans {
if p != nil && p.DeptID == dept {
scoped = append(scoped, p)
}
}
plans = scoped
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": plans})
}
// DemandProgress GET /training/annual-plans/progress — 年度需求收集进度
// (课长本部门口径:纯课长仅看本部门行)。
func (h *Handler) DemandProgress(c *gin.Context) {
year, _ := strconv.Atoi(c.Query("year"))
rows, err := h.svc.DeptDemandProgress(c.Request.Context(), callerTenantID(c), year)
if err != nil {
_ = c.Error(err)
return
}
if dept := h.callerDeptScope(c); dept != "" {
scoped := make([]*types.TrainingDeptProgress, 0, len(rows))
for _, row := range rows {
if row != nil && row.DeptID == dept {
scoped = append(scoped, row)
}
}
rows = scoped
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": rows})
}
// ListMonthPlans GET /training/month-plans — 课长本部门口径:纯课长仅本部门月度计划。
func (h *Handler) ListMonthPlans(c *gin.Context) {
q := listQueryFromRequest(c)
if dept := h.callerDeptScope(c); dept != "" {
q.DeptID = dept
}
plans, err := h.svc.ListMonthPlans(c.Request.Context(), callerTenantID(c), q)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": plans})
}
// saveMonthPlanRequest is the body of POST /training/month-plans.
type saveMonthPlanRequest struct {
ID string `json:"id"`
Year int `json:"year"`
Month int `json:"month"`
DeptID string `json:"dept_id"`
Title string `json:"title" binding:"required"`
StartAt string `json:"start_at"` // RFC3339 / "2006-01-02 15:04"
Location string `json:"location"`
LecturerID string `json:"lecturer_id"`
}
// SaveMonthPlan POST /training/month-plans — 人事/课长排课。
func (h *Handler) SaveMonthPlan(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req saveMonthPlanRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
startAt := parseFlexibleTime(req.StartAt)
plan, err := h.svc.SaveMonthPlan(ctx, callerTenantID(c), &types.TrainingMonthPlan{
ID: req.ID, Year: req.Year, Month: req.Month, DeptID: req.DeptID,
Title: req.Title, StartAt: startAt, Location: req.Location,
LecturerID: req.LecturerID, SubmitterID: callerUserID(c),
})
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": plan})
}
// ApproveMonthPlan POST /training/month-plans/:id/approve — 主管审批。
func (h *Handler) ApproveMonthPlan(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleManager, types.TrainingRoleHR) {
return
}
var req struct {
Action string `json:"action" binding:"required"` // pass | adjust | reject
Reason string `json:"reason"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
plan, err := h.svc.ApproveMonthPlan(ctx, callerTenantID(c), c.Param("id"), req.Action, req.Reason, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": plan})
}
// RollMonthPlans POST /training/month-plans/roll — 月底滚动生成下月计划。
func (h *Handler) RollMonthPlans(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR) {
return
}
var req struct {
Year int `json:"year"`
Month int `json:"month"`
}
_ = c.ShouldBindJSON(&req)
rolled, err := h.svc.RollMonthPlans(ctx, callerTenantID(c), req.Year, req.Month, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"rolled": rolled}})
}
// ---------------------------------------------------------------------------
// 课程域
// ---------------------------------------------------------------------------
// ListCourses GET /training/courses — 数据范围:
// - 全局视角(人事/课长/经理/空间管理员):按请求参数过滤;
// - 学员目录视图(scope=student):统一只看已发布课程;
// - 课程维护视角(默认):纯讲师仅自己讲师相关的课程(含草稿,供维护);
// 纯学员仅已发布课程。
func (h *Handler) ListCourses(c *gin.Context) {
q := listQueryFromRequest(c)
scope, _ := h.callerDataScope(c)
switch {
case scope == scopeManager:
// 全局视角,不收窄
case q.Scope == "student":
// 学员目录视图:讲师/学员统一只看已发布课程
q.Status = types.TrainingCoursePublished
case scope == scopeLecturer:
// 课程维护列表:纯讲师仅自己相关的课程
q.LecturerID = callerUserID(c)
case scope == scopeTrainee:
q.Status = types.TrainingCoursePublished
}
items, total, err := h.svc.ListCourses(c.Request.Context(), callerTenantID(c), q)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": items, "total": total}})
}
// GetCourse GET /training/courses/:id — 详情同样按数据范围校验(见 checkCourseVisibility)。
func (h *Handler) GetCourse(c *gin.Context) {
course, err := h.svc.GetCourse(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if err := h.checkCourseVisibility(c, course); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": course})
}
// saveCourseRequest is the body of POST /training/courses.
type saveCourseRequest struct {
ID string `json:"id"`
Code string `json:"code"`
Name string `json:"name" binding:"required"`
Mode string `json:"mode"`
Type string `json:"type"`
LecturerID string `json:"lecturer_id"`
Hours float64 `json:"hours"`
Credits float64 `json:"credits"`
ExamEnabled bool `json:"exam_enabled"`
DeptIDs []string `json:"dept_ids"`
PostScope string `json:"post_scope"`
Description string `json:"description"`
MaterialIDs []string `json:"material_ids"`
TeachTime string `json:"teach_time"`
// PlannedTime 计划培训时间(需求确认同步的课程携带;前端编辑时原样回传保留)。
PlannedTime string `json:"planned_time"`
QuestionBankID string `json:"question_bank_id"`
// 以下为需求确认同步字段(前端编辑时原样回传保留,防止被零值覆盖)。
TrainType string `json:"train_type"`
Plant string `json:"plant"`
Location string `json:"location"`
SessionCount int `json:"session_count"`
LecturerExternal string `json:"lecturer_external"`
Remark string `json:"remark"`
// LibraryCourseID 课程管理条目 id(月培训计划「计划名称」选择课程后关联)。
LibraryCourseID string `json:"library_course_id"`
}
// SaveCourse POST /training/courses — 课程创建(线下/线上双向导数据源)。
// 携带 question_bank_id 时反向绑定题库(建课时任选题库)。
func (h *Handler) SaveCourse(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req saveCourseRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
course, err := h.svc.SaveCourse(ctx, callerTenantID(c), &types.TrainingCourse{
ID: req.ID, Code: req.Code, Name: req.Name, Mode: req.Mode, Type: req.Type,
LecturerID: req.LecturerID, Hours: req.Hours, Credits: req.Credits,
ExamEnabled: req.ExamEnabled, DeptIDs: sliceToJSON(req.DeptIDs),
PostScope: req.PostScope, Description: req.Description,
MaterialIDs: sliceToJSON(req.MaterialIDs), TeachTime: req.TeachTime,
PlannedTime: req.PlannedTime,
TrainType: req.TrainType, Plant: req.Plant, Location: req.Location,
SessionCount: req.SessionCount, LecturerExternal: req.LecturerExternal, Remark: req.Remark,
LibraryCourseID: req.LibraryCourseID,
}, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
// 每一位员工都可能是讲师:选定讲师后自动补齐 lecturer 角色绑定(fail-open)。
if err := h.svc.EnsureLecturerRole(ctx, callerTenantID(c), course.LecturerID); err != nil {
logger.Error(ctx, "Failed to ensure lecturer role", err)
}
if err := h.svc.AttachQuestionBank(ctx, callerTenantID(c), course.ID, req.QuestionBankID, callerUserID(c)); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": course})
}
// PublishCourse POST /training/courses/:id/publish
func (h *Handler) PublishCourse(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
// 发布前置校验:线上课程必须有课件资料,线下课程必须指定讲师。
course, err := h.svc.GetCourse(ctx, callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if course.Mode == "online" {
materials, err := h.svc.ListMaterials(ctx, callerTenantID(c), course.ID)
if err != nil {
_ = c.Error(err)
return
}
if len(materials) == 0 {
_ = c.Error(errors.NewBadRequestError("线上课程发布前需先登记课件资料(上传课件/从课件库选择/仅登记名称)"))
return
}
} else if trimSpace(course.LecturerID) == "" {
_ = c.Error(errors.NewBadRequestError("线下课程发布前需先指定讲师"))
return
}
published, err := h.svc.PublishCourse(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": published})
}
// DeleteCourse DELETE /training/courses/:id
func (h *Handler) DeleteCourse(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
if err := h.svc.DeleteCourse(ctx, callerTenantID(c), c.Param("id")); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// GetCourseChangeLogs GET /training/courses/:id/change-logs — 课程信息修改版本记录。
func (h *Handler) GetCourseChangeLogs(c *gin.Context) {
items, err := h.svc.ListCourseChangeLogs(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// ImportQuestionBankFromKnowledge POST /training/question-banks/import-from-kb
// — 从「企业培训(题库)」知识库文档解析建题库(课程详情「从知识库选择」入口)。
func (h *Handler) ImportQuestionBankFromKnowledge(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleLecturer) {
return
}
var req struct {
KnowledgeID string `json:"knowledge_id" binding:"required"`
Name string `json:"name"`
CourseID string `json:"course_id"`
LibraryCourseID string `json:"library_course_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
bank, err := h.svc.ImportQuestionBankFromKnowledge(ctx, callerTenantID(c), req.KnowledgeID, req.Name, req.CourseID, req.LibraryCourseID, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": bank})
}
// AnswerPaperQuestion POST /training/papers/:id/answer — 单题即时判分(答题实时反馈)。
func (h *Handler) AnswerPaperQuestion(c *gin.Context) {
var req struct {
QuestionID string `json:"question_id" binding:"required"`
Answer string `json:"answer"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
feedback, err := h.svc.AnswerQuestion(c.Request.Context(), callerTenantID(c), c.Param("id"), req.QuestionID, req.Answer)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": feedback})
}
// ListCoursePapers GET /training/courses/:id/papers — 课程维度试卷列表(场次卷+线上自学卷)。
func (h *Handler) ListCoursePapers(c *gin.Context) {
items, err := h.svc.ListPapersForCourse(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// ListPaperRecords GET /training/papers/:id/records — 单张试卷的答题记录(按试卷查询)。
func (h *Handler) ListPaperRecords(c *gin.Context) {
items, err := h.svc.ListPaperRecords(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// GenerateCourseQuestions POST /training/courses/:id/generate-questions
// — AI 课件生成试题:按课件知识库分块出题(预览编辑用,不落库)。
func (h *Handler) GenerateCourseQuestions(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleLecturer) {
return
}
var req struct {
MaterialID string `json:"material_id" binding:"required"`
Count int `json:"count"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
questions, err := h.svc.GenerateCourseQuestions(ctx, callerTenantID(c), callerUserID(c), c.Param("id"), req.MaterialID, req.Count)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": questions})
}
// ImportGeneratedQuestionBank POST /training/question-banks/import-generated
// — 使用(AI 生成并经编辑的)题目建题库,关联课程并同步知识库。
func (h *Handler) ImportGeneratedQuestionBank(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleLecturer) {
return
}
var req struct {
CourseID string `json:"course_id"`
LibraryCourseID string `json:"library_course_id"`
Name string `json:"name"`
Questions []*types.TrainingQuestion `json:"questions" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
bank, err := h.svc.ImportGeneratedQuestionBank(ctx, callerTenantID(c), req.CourseID, req.LibraryCourseID, req.Name, req.Questions, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": bank})
}
// ListSessions GET /training/sessions — 学员目录视图(scope=student)不收窄;
// 课程维护视角下纯讲师仅自己讲师相关的场次。
func (h *Handler) ListSessions(c *gin.Context) {
q := listQueryFromRequest(c)
if scope, _ := h.callerDataScope(c); scope == scopeLecturer && q.Scope != "student" {
q.LecturerID = callerUserID(c)
}
items, err := h.svc.ListSessions(c.Request.Context(), callerTenantID(c), q)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// saveSessionRequest is the body of POST /training/sessions.
type saveSessionRequest struct {
ID string `json:"id"`
CourseID string `json:"course_id" binding:"required"`
MonthPlanID string `json:"month_plan_id"`
StartAt string `json:"start_at"`
EndAt string `json:"end_at"`
Location string `json:"location"`
OnlineURL string `json:"online_url"`
Capacity int `json:"capacity"`
LecturerID string `json:"lecturer_id"`
// NotifyMode 学员开课通知方式: immediate(默认,名单/课件就绪即推)/
// day_before(调度器开课前 1 天推);非法值落库前归一化为 immediate。
NotifyMode string `json:"notify_mode"`
}
// SaveSession POST /training/sessions — 排课信息(时间/地点/讲师档期)。
func (h *Handler) SaveSession(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req saveSessionRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if req.NotifyMode != types.TrainingNotifyModeDayBefore {
req.NotifyMode = types.TrainingNotifyModeImmediate
}
session, err := h.svc.SaveSession(ctx, callerTenantID(c), &types.TrainingCourseSession{
ID: req.ID, CourseID: req.CourseID, MonthPlanID: req.MonthPlanID,
StartAt: parseFlexibleTime(req.StartAt), EndAt: parseFlexibleTime(req.EndAt),
Location: req.Location, OnlineURL: req.OnlineURL,
Capacity: req.Capacity, LecturerID: req.LecturerID,
NotifyMode: req.NotifyMode,
}, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": session})
}
// SetEnrollments PUT /training/sessions/:id/enrollments — 学员范围批量设置。
func (h *Handler) SetEnrollments(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
MemberIDs []string `json:"member_ids" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
roster, err := h.svc.SetEnrollments(ctx, callerTenantID(c), c.Param("id"), req.MemberIDs)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": roster})
}
// SetEnrollmentResult POST /training/enrollments/:id/result — 完成状态/归因回填。
func (h *Handler) SetEnrollmentResult(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
Status string `json:"status" binding:"required"`
Reason string `json:"reason"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
enrollment, err := h.svc.SetEnrollmentResult(ctx, callerTenantID(c), c.Param("id"), req.Status, req.Reason, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": enrollment})
}
// ListEnrollments GET /training/sessions/:id/enrollments
func (h *Handler) ListEnrollments(c *gin.Context) {
roster, err := h.svc.ListEnrollmentsForSession(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": roster})
}
// CreateMaterial POST /training/materials — 课件元数据登记。
func (h *Handler) CreateMaterial(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
var req struct {
CourseID string `json:"course_id"`
Kind string `json:"kind"`
Name string `json:"name" binding:"required"`
FileKey string `json:"file_key"`
KnowledgeID string `json:"knowledge_id"`
Size int64 `json:"size"`
Duration int `json:"duration"`
Tags []string `json:"tags"`
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
material, err := h.svc.CreateMaterial(ctx, callerTenantID(c), &types.TrainingMaterial{
CourseID: req.CourseID, Kind: req.Kind, Name: req.Name,
FileKey: req.FileKey, KnowledgeID: req.KnowledgeID,
Size: req.Size, Duration: req.Duration, Tags: sliceToJSON(req.Tags),
}, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": material})
}
// ListMaterials GET /training/materials?course_id= — 按课程可见性收窄
// (纯讲师/纯学员不能通过 course_id 绕过未发布课程的数据范围)。
func (h *Handler) ListMaterials(c *gin.Context) {
if courseID := c.Query("course_id"); courseID != "" {
course, err := h.svc.GetCourse(c.Request.Context(), callerTenantID(c), courseID)
if err != nil {
_ = c.Error(err)
return
}
if err := h.checkCourseVisibility(c, course); err != nil {
_ = c.Error(err)
return
}
}
items, err := h.svc.ListMaterials(c.Request.Context(), callerTenantID(c), c.Query("course_id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// trainingVideoMaxSizeMB 视频类课件容量上限:视频普遍大于文档,单独放宽。
const trainingVideoMaxSizeMB = 200
// isVideoUploadName 与 service 层 isVideoMaterialFile 同口径的扩展名判断(handler 层限流用)。
func isVideoUploadName(filename, kind string) bool {
if strings.EqualFold(strings.TrimSpace(kind), "video") {
return true
}
switch strings.ToLower(filepath.Ext(filename)) {
case ".mp4", ".webm", ".mov", ".m4v", ".mkv", ".avi":
return true
}
return false
}
// UploadMaterial POST /training/materials/upload — 课件文件上传(multipart):
// 文档自动同步进系统默认「企业培训(课件)」知识库并回填 knowledge_id,
// 与知识库直传共用同一解析/向量化链路,从而支持 AI 对话问答;
// 视频不入知识库,只存原始文件回填 file_key,学习详情页流式播放。
func (h *Handler) UploadMaterial(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
fh, err := c.FormFile("file")
if err != nil {
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
return
}
// 容量上限:文档与知识库直传一致(MAX_FILE_SIZE_MB,默认 50MB);视频单独放宽到 200MB。
maxSizeMB := utils.GetMaxFileSizeMB()
if isVideoUploadName(fh.Filename, c.PostForm("kind")) {
maxSizeMB = trainingVideoMaxSizeMB
}
if fh.Size > maxSizeMB*1024*1024 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", maxSizeMB)))
return
}
material, err := h.svc.UploadMaterial(ctx, callerTenantID(c), fh,
c.PostForm("course_id"), c.PostForm("kind"), c.PostForm("name"), callerUserID(c))
if err != nil {
logger.Error(ctx, "Failed to upload training material", err)
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": material})
}
// MaterialFile GET /training/materials/:id/file — 课件文件流:文档经知识库
// 取回,视频按 file_key 直取原始文件(学习详情页在线播放)。
func (h *Handler) MaterialFile(c *gin.Context) {
rc, fileName, err := h.svc.GetMaterialFile(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
// filetransport.Serve 自带 Close;inline 按扩展名安全判断(视频 mp4 → video/mp4)。
if err := filetransport.Serve(c.Writer, c.Request, rc, filetransport.Options{Filename: fileName}); err != nil {
_ = c.Error(err)
}
}
// ListTrainingKnowledgeBases GET /training/knowledge-bases — 返回(并按需惰性
// 创建)系统默认的两个企业培训知识库,供建课弹窗「从课件库选择」等场景使用。
func (h *Handler) ListTrainingKnowledgeBases(c *gin.Context) {
kbs, err := h.svc.ListTrainingKnowledgeBases(c.Request.Context())
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": kbs})
}
// ---------------------------------------------------------------------------
// 签到域
// ---------------------------------------------------------------------------
// CreateSignCode POST /training/sessions/:id/sign-code — 开课前生成签到码。
func (h *Handler) CreateSignCode(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
GeoLat float64 `json:"geo_lat"`
GeoLng float64 `json:"geo_lng"`
GeoRadius int `json:"geo_radius"`
}
_ = c.ShouldBindJSON(&req)
code, err := h.svc.CreateSignCode(ctx, callerTenantID(c), c.Param("id"), req.GeoLat, req.GeoLng, req.GeoRadius, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": code})
}
// GetSignCode GET /training/sessions/:id/sign-code
func (h *Handler) GetSignCode(c *gin.Context) {
code, err := h.svc.GetSignCode(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": code})
}
// CheckinRequest is the body of POST /training/sign-records/checkin.
type CheckinRequest struct {
Token string `json:"token" binding:"required"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
Channel string `json:"channel"`
// MemberID 可选:讲师/课长/人事现场代扫码/补录。
MemberID string `json:"member_id"`
}
// Checkin POST /training/sign-records/checkin — 学员扫码签到(带定位校验);
// 带 member_id 时为讲师/管理角色代录,走同一规则引擎并留 proxy 标记。
func (h *Handler) Checkin(c *gin.Context) {
ctx := c.Request.Context()
var req CheckinRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if req.MemberID != "" {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
record, err := h.svc.CheckinFor(ctx, callerTenantID(c), callerUserID(c), req.Token, req.MemberID, req.Lat, req.Lng, req.Channel)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
return
}
record, err := h.svc.Checkin(ctx, callerTenantID(c), callerUserID(c), req.Token, req.Lat, req.Lng, req.Channel)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
}
// ListSignRecords GET /training/sessions/:id/sign-records — 签到明细。
func (h *Handler) ListSignRecords(c *gin.Context) {
items, err := h.svc.ListSignRecords(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// ReviewSignRecord POST /training/sign-records/:id/review — 异常复核。
func (h *Handler) ReviewSignRecord(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req struct {
Decision string `json:"decision" binding:"required"` // confirm | reject
}
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
record, err := h.svc.ReviewSignRecord(ctx, callerTenantID(c), c.Param("id"), req.Decision, callerUserID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": record})
}
// SignSummary GET /training/sessions/:id/sign-summary — 应到/已到/迟到/异常。
func (h *Handler) SignSummary(c *gin.Context) {
summary, err := h.svc.SignSummary(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": summary})
}
// ExportEvidenceRequest is the body of POST /training/evidence/export.
type ExportEvidenceRequest struct {
SessionIDs []string `json:"session_ids" binding:"required,min=1"`
}
// ExportEvidence POST /training/evidence/export — 请款佐证包 xlsx 下载。
func (h *Handler) ExportEvidence(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
var req ExportEvidenceRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
filename, data, err := h.svc.ExportEvidence(ctx, callerTenantID(c), req.SessionIDs)
if err != nil {
_ = c.Error(err)
return
}
c.Header("Content-Disposition", "attachment; filename="+filename)
c.Data(http.StatusOK, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", data)
}
// ---------------------------------------------------------------------------
// 培训佐证文件(签到照/培训视频)
// ---------------------------------------------------------------------------
// UploadSessionEvidence POST /training/sessions/:id/evidence — 上传线下课
// 佐证文件(multipart: file + kind=sign_photo|training_video + name 可选)。
// 照片按文档上限,视频放宽到 200MB(与课件视频一致)。
func (h *Handler) UploadSessionEvidence(c *gin.Context) {
ctx := c.Request.Context()
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor, types.TrainingRoleLecturer) {
return
}
fh, err := c.FormFile("file")
if err != nil {
_ = c.Error(errors.NewBadRequestError("缺少上传文件"))
return
}
kind := c.PostForm("kind")
maxSizeMB := utils.GetMaxFileSizeMB()
if kind == types.TrainingEvidenceTrainVideo || isVideoUploadName(fh.Filename, "") {
maxSizeMB = trainingVideoMaxSizeMB
}
if fh.Size > maxSizeMB*1024*1024 {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("文件大小不能超过%dMB", maxSizeMB)))
return
}
evidence, err := h.svc.UploadSessionEvidence(ctx, callerTenantID(c), c.Param("id"), fh,
kind, c.PostForm("name"), callerUserID(c))
if err != nil {
logger.Error(ctx, "Failed to upload session evidence", err)
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": evidence})
}
// ListSessionEvidence GET /training/sessions/:id/evidence — 场次佐证文件列表。
func (h *Handler) ListSessionEvidence(c *gin.Context) {
items, err := h.svc.ListSessionEvidences(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// SessionEvidenceFile GET /training/session-evidences/:id/file — 佐证文件流
// (照片/视频 inline 预览,mp4 按扩展名安全判断)。
func (h *Handler) SessionEvidenceFile(c *gin.Context) {
rc, fileName, err := h.svc.GetSessionEvidenceFile(c.Request.Context(), callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
if err := filetransport.Serve(c.Writer, c.Request, rc, filetransport.Options{Filename: fileName}); err != nil {
_ = c.Error(err)
}
}
// DeleteSessionEvidence DELETE /training/session-evidences/:id — 删除佐证记录
// (人事/课长;对象文件保留以留证)。
func (h *Handler) DeleteSessionEvidence(c *gin.Context) {
if !h.requireRoles(c, types.TrainingRoleHR, types.TrainingRoleSupervisor) {
return
}
if err := h.svc.DeleteSessionEvidence(c.Request.Context(), callerTenantID(c), c.Param("id"), callerUserID(c)); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}