Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s
- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名) - 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块) - docreader proto 描述符采用等长替换,保持序列化字节布局有效 - Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像 - 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
1580 lines
57 KiB
Go
1580 lines
57 KiB
Go
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) ||
|
||
types.HasTrainingRole(roles, types.TrainingRoleManager) ||
|
||
!types.HasTrainingRole(roles, types.TrainingRoleSupervisor) {
|
||
return ""
|
||
}
|
||
return member.DeptID
|
||
}
|
||
|
||
// 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()
|
||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||
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
|
||
func (h *Handler) UpdateMemberRoles(c *gin.Context) {
|
||
ctx := c.Request.Context()
|
||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||
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}})
|
||
}
|
||
|
||
// 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
|
||
}
|
||
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,
|
||
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
|
||
}
|
||
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": len(result)}})
|
||
}
|
||
|
||
// ConfirmDemand POST /training/demands/:id/confirm — 人事复核确认。
|
||
func (h *Handler) ConfirmDemand(c *gin.Context) {
|
||
ctx := c.Request.Context()
|
||
if !h.requireRoles(c, types.TrainingRoleHR) {
|
||
return
|
||
}
|
||
demand, err := h.svc.ConfirmDemand(ctx, callerTenantID(c), c.Param("id"), callerUserID(c))
|
||
if err != nil {
|
||
_ = c.Error(err)
|
||
return
|
||
}
|
||
// 已确认需求自动生成草稿课程到课程管理(fail-open,不阻断确认)。
|
||
h.syncDemandCourse(ctx, callerTenantID(c), demand, callerUserID(c))
|
||
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,
|
||
}
|
||
// 授课时间默认取需求「期望月份」(YYYY-MM,课程管理侧可修改并留版本记录)。
|
||
if demand.Year > 0 && demand.ExpectMonth >= 1 && demand.ExpectMonth <= 12 {
|
||
course.TeachTime = fmt.Sprintf("%04d-%02d", demand.Year, demand.ExpectMonth)
|
||
}
|
||
// 计划培训时间:需求已填则原样同步到课程(YYYY-MM-DD HH:mm / YYYY-MM-DD)。
|
||
course.PlannedTime = 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
|
||
}
|
||
|
||
// 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"`
|
||
}
|
||
|
||
// 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,
|
||
}, 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"`
|
||
}
|
||
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, 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"`
|
||
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.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})
|
||
}
|