Files
runny 448fbcdaff
deploy-hxtesting / build-and-deploy (push) Successful in 1m13s
feat(org): 组织架构新增「收编到本空间」,批量修正成员登录默认落点
员工首登自动开通个人空间(create_personal 默认)后,归属空间(users.tenant_id)
与「最近活跃租户」偏好停在个人空间,登录后看到的是个人空间里那份空的组织
架构/培训数据,模板下载也没有部门下拉。空间 Owner 现可一键收编:
1. GET /org/employees/adoptable 收编预览:归属空间不在本空间的活跃成员
   (COALESCE 兜底 NULL 归属,联查名册标记与归属空间名供确认);
2. POST /org/employees/adopt-home 批量收编:逐条校验不整批失败,非本空间
   成员/停用/跨空间账号/已归属本空间逐条跳过并回传原因;归属指针与最近
   活跃租户偏好一起改指本空间(登录路径优先读偏好,只改归属会被旧偏好
   拉回),成员关系/角色/个人空间数据不动,可经空间切换器改回,非破坏性;
3. 收编成功者补跑自动入册(EnsureEmployeesForUsers 仅补空幂等),
   同步部门自动匹配进名册;
4. 单条 rbac.member_home_adopted 审计(best-effort);路由 g.Owner() 限定,
   与成员批量导入/Casdoor 同步同权限级别;
5. 收编依赖只引 repository 层(UserRepository/TenantMemberRepository),
   避开 tenantMemberService→OrgCenterService→userService→memberService
   的 DI 环;
6. 前端组织架构页新增「收编到本空间」入口(仅 hasRole('owner') 可见)+
   预览确认弹窗(与 OA 同步弹窗同两段式交互);顺手补齐
   OrgEmployee.wecom_userid 缺失的存量类型缺口(type-check 阻断项)。
测试:服务层新增收编落点+偏好/六类跳过/守卫 3 例;仓库层 sqlite 用例覆盖
NULL 归属兜底与停用/已归属排除;既有 org/member/casdoor/培训模板用例无回归。
2026-11-24 18:16:51 +08:00

325 lines
11 KiB
Go

package orgcenter
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// Handler 组织中心 HTTP 处理器。权限模型:
// - 组织架构为租户级共享数据,读写由空间 RBAC 把关(路由层 Viewer 读 / Contributor 写);
// - 各业务模块的角色绑定(module_key)由模块自己的接口/handler 细控,
// 本层不感知培训等模块的业务角色语义。
type Handler struct {
svc interfaces.OrgCenterService
}
// NewHandler constructs the org center handler.
func NewHandler(svc interfaces.OrgCenterService) *Handler {
return &Handler{svc: svc}
}
// callerTenantID reads the tenant id injected by the auth middleware.
func callerTenantID(c *gin.Context) uint64 {
return c.GetUint64(types.TenantIDContextKey.String())
}
// orgListQueryFromRequest parses the common list filters from the request.
func orgListQueryFromRequest(c *gin.Context) *types.OrgListQuery {
q := &types.OrgListQuery{
DeptID: c.Query("dept_id"),
Keyword: c.Query("keyword"),
}
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
}
// ---------------------------------------------------------------------------
// 部门
// ---------------------------------------------------------------------------
// ListDepts GET /org/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 /org/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 /org/depts (id 非空走更新)
func (h *Handler) SaveDept(c *gin.Context) {
ctx := c.Request.Context()
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.OrgDept{
ID: req.ID, ParentID: req.ParentID, Name: req.Name, Code: req.Code, Sort: req.Sort,
})
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": dept})
}
// DeleteDept DELETE /org/depts/:id
func (h *Handler) DeleteDept(c *gin.Context) {
ctx := c.Request.Context()
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})
}
// ---------------------------------------------------------------------------
// 员工档案
// ---------------------------------------------------------------------------
// ListEmployees GET /org/employees?module_key=&dept_id=&keyword=&page=&page_size=
// module_key 可选:传入时附加该模块的绑定角色展示(如 training)。
func (h *Handler) ListEmployees(c *gin.Context) {
employees, total, err := h.svc.ListEmployees(
c.Request.Context(), callerTenantID(c), c.Query("module_key"), orgListQueryFromRequest(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"items": employees, "total": total}})
}
// importEmployeeItem is one row of the employee import payload.
type importEmployeeItem struct {
UserID string `json:"user_id" binding:"required"`
EmployeeNo string `json:"employee_no"`
DeptID string `json:"dept_id" binding:"required"`
Post string `json:"post"`
WecomUserid string `json:"wecom_userid"`
Status string `json:"status"`
}
// ImportEmployeesRequest is the body of POST /org/employees/import.
type ImportEmployeesRequest struct {
Employees []importEmployeeItem `json:"employees" binding:"required,min=1"`
}
// ImportEmployees POST /org/employees/import (部门必填,服务层校验命中)
func (h *Handler) ImportEmployees(c *gin.Context) {
ctx := c.Request.Context()
var req ImportEmployeesRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
employees := make([]*types.OrgEmployee, 0, len(req.Employees))
for _, item := range req.Employees {
employees = append(employees, &types.OrgEmployee{
UserID: item.UserID,
EmployeeNo: item.EmployeeNo,
DeptID: item.DeptID,
Post: item.Post,
WecomUserid: item.WecomUserid,
Status: item.Status,
})
}
count, err := h.svc.ImportEmployees(ctx, callerTenantID(c), employees)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"imported": count}})
}
// updateEmployeeRequest is the body of PUT /org/employees/:id.
// 姓名/工号随平台账号维护,不在可编辑范围;部门必填(与导入同规)。
type updateEmployeeRequest struct {
DeptID string `json:"dept_id" binding:"required"`
Post string `json:"post"`
Status string `json:"status"`
}
// UpdateEmployee PUT /org/employees/:id — 修改员工档案。
// Read-modify-write:先取现有档案再覆盖可编辑字段,wecom_userid/lecturer_rate
// 等由 OA 同步/业务模块维护的字段保持不动;状态留空表示不变更。
func (h *Handler) UpdateEmployee(c *gin.Context) {
ctx := c.Request.Context()
var req updateEmployeeRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
employee, err := h.svc.GetEmployee(ctx, callerTenantID(c), c.Param("id"))
if err != nil {
_ = c.Error(err)
return
}
employee.DeptID = req.DeptID
employee.Post = req.Post
if req.Status != "" {
employee.Status = req.Status
}
updated, err := h.svc.UpdateEmployee(ctx, callerTenantID(c), employee)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": updated})
}
// ListPlatformUsers GET /org/platform-users — 员工导入的用户选择器数据源。
func (h *Handler) ListPlatformUsers(c *gin.Context) {
users, err := h.svc.ListTenantUsers(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
}
// ---------------------------------------------------------------------------
// 归属空间收编(登录默认落点;路由层 Owner 限定,与成员批量导入同权限级别)
// ---------------------------------------------------------------------------
// orgAdoptMaxUsers 单次收编人数上限(与成员批量导入行数上限同量级,防超大批次)。
const orgAdoptMaxUsers = 2000
// ListAdoptableUsers GET /org/employees/adoptable — 收编预览:归属空间不在
// 本空间的活跃成员(员工首登开了个人空间时,登录会落进个人空间看不到本空间
// 维护的组织架构,管理员用收编把默认落点改回本空间)。
func (h *Handler) ListAdoptableUsers(c *gin.Context) {
users, err := h.svc.ListAdoptableUsers(c.Request.Context(), callerTenantID(c))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": users})
}
// adoptHomeTenantRequest is the body of POST /org/employees/adopt-home.
type adoptHomeTenantRequest struct {
UserIDs []string `json:"user_ids" binding:"required,min=1"`
}
// AdoptHomeTenant POST /org/employees/adopt-home — 批量收编归属空间到本空间。
// 只改成员的登录默认落点(users.tenant_id + 最近活跃租户偏好),不动成员关系
// 与个人空间数据;逐条跳过非本空间成员等情形并回传原因。
func (h *Handler) AdoptHomeTenant(c *gin.Context) {
ctx := c.Request.Context()
var req adoptHomeTenantRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if len(req.UserIDs) > orgAdoptMaxUsers {
_ = c.Error(errors.NewBadRequestError(fmt.Sprintf("单次最多收编 %d 名成员", orgAdoptMaxUsers)))
return
}
// 去重保序:重复/空 id 只收编一次,统计口径不重复计数。
seen := make(map[string]struct{}, len(req.UserIDs))
userIDs := make([]string, 0, len(req.UserIDs))
for _, id := range req.UserIDs {
if id == "" {
continue
}
if _, dup := seen[id]; dup {
continue
}
seen[id] = struct{}{}
userIDs = append(userIDs, id)
}
if len(userIDs) == 0 {
_ = c.Error(errors.NewBadRequestError("请选择要收编的成员"))
return
}
result, err := h.svc.AdoptHomeTenant(ctx, callerTenantID(c), userIDs)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
// ---------------------------------------------------------------------------
// 模块角色绑定
// ---------------------------------------------------------------------------
// ListModuleMembers GET /org/modules/:module_key/members
func (h *Handler) ListModuleMembers(c *gin.Context) {
members, err := h.svc.ListModuleMembers(
c.Request.Context(), callerTenantID(c), c.Param("module_key"))
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": members})
}
// putModuleMemberRequest is the body of PUT /org/modules/:module_key/members/:employee_id.
type putModuleMemberRequest struct {
Roles []string `json:"roles"`
Extra map[string]any `json:"extra"`
}
// PutModuleMember PUT /org/modules/:module_key/members/:employee_id
func (h *Handler) PutModuleMember(c *gin.Context) {
ctx := c.Request.Context()
var req putModuleMemberRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
member, err := h.svc.PutModuleMember(ctx, callerTenantID(c), &types.OrgModuleMember{
ModuleKey: c.Param("module_key"),
EmployeeID: c.Param("employee_id"),
Roles: orgJSONFromRoles(req.Roles),
Extra: orgJSONFromAny(req.Extra),
})
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": member})
}
// orgJSONFromRoles encodes a role list as the roles jsonb payload.
func orgJSONFromRoles(roles []string) types.JSON {
if roles == nil {
roles = []string{}
}
data, _ := json.Marshal(roles)
return types.JSON(data)
}
// orgJSONFromAny encodes an arbitrary map as the extra jsonb payload.
func orgJSONFromAny(extra map[string]any) types.JSON {
if extra == nil {
extra = map[string]any{}
}
data, _ := json.Marshal(extra)
return types.JSON(data)
}