Files
full/module/base/mgt/internal/logic/department/list.go

85 lines
2.3 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 department
import (
"bsm/full/module/base/mgt/internal/impl"
"bsm/full/module/base/mgt/internal/libs"
"bsm/full/module/base/mgt/internal/models"
"bsm/full/module/base/mgt/internal/types"
"git.apinb.com/bsm-sdk/core/errcode"
"git.apinb.com/bsm-sdk/core/infra"
"git.apinb.com/bsm-sdk/core/printer"
"github.com/gin-gonic/gin"
)
// List 下拉用部门列表,必传 workspacetree=true 时返回树形
func List(c *gin.Context) {
var (
request = types.DptReq{}
data = make([]models.MgtDepartment, 0)
)
if err := c.ShouldBindJSON(&request); err != nil {
infra.Response.Error(c, errcode.ErrJsonUnmarshal)
return
}
if err := libs.ValidateStruct(&request); err != nil {
infra.Response.Error(c, errcode.ErrInvalidArgument)
return
}
if request.Workspace == "" {
printer.Error("部门列表参数异常: workspace 不能为空")
infra.Response.Error(c, errcode.ErrInvalidArgument)
return
}
appModel := models.MgtApplication{Workspace: request.Workspace}
appId, err := appModel.WorkspaceToId()
if err != nil {
printer.Error("未获取到应用: workspace=%s", request.Workspace)
infra.Response.Error(c, errcode.ErrRecordNotFound)
return
}
db := impl.DBService.Model(&models.MgtDepartment{}).
Where("app_id = ?", appId).
Select("id", "identity", "name", "app_id", "parent_id")
if request.Keyword != "" {
db = db.Where("name LIKE ?", "%"+request.Keyword+"%")
}
if request.Status != 0 {
db = db.Where("status = ?", request.Status)
}
if request.Tree {
if err := db.Order("parent_id asc").Find(&data).Error; err != nil {
infra.Response.Error(c, errcode.ErrDB)
return
}
tree := buildDeptTree(data, 0)
infra.Response.Success(c, types.FetchResp{Data: tree})
return
}
if err := db.Order("parent_id asc").Find(&data).Error; err != nil {
infra.Response.Error(c, errcode.ErrDB)
return
}
infra.Response.Success(c, types.FetchResp{Data: data})
}
// buildDeptTree 将扁平部门列表按 parent_id 建树parentId 为根节点父ID0 表示顶层)
func buildDeptTree(list []models.MgtDepartment, parentId uint) []models.MgtDepartment {
var node []models.MgtDepartment
for _, d := range list {
if d.ParentID != parentId {
continue
}
children := buildDeptTree(list, d.ID)
if len(children) > 0 {
d.Children = children
}
node = append(node, d)
}
return node
}