| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package dept
- import (
- "context"
- "perms-system-server/internal/svc"
- "perms-system-server/internal/types"
- "github.com/zeromicro/go-zero/core/logx"
- )
- type DeptTreeLogic struct {
- logx.Logger
- ctx context.Context
- svcCtx *svc.ServiceContext
- }
- func NewDeptTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptTreeLogic {
- return &DeptTreeLogic{
- Logger: logx.WithContext(ctx),
- ctx: ctx,
- svcCtx: svcCtx,
- }
- }
- func (l *DeptTreeLogic) DeptTree() (resp []*types.DeptItem, err error) {
- list, err := l.svcCtx.SysDeptModel.FindAll(l.ctx)
- if err != nil {
- return nil, err
- }
- items := make([]*types.DeptItem, 0, len(list))
- for _, d := range list {
- items = append(items, &types.DeptItem{
- Id: d.Id,
- ParentId: d.ParentId,
- Name: d.Name,
- Path: d.Path,
- Sort: d.Sort,
- DeptType: d.DeptType,
- Remark: d.Remark,
- Status: d.Status,
- CreateTime: d.CreateTime,
- Children: make([]*types.DeptItem, 0),
- })
- }
- itemMap := make(map[int64]*types.DeptItem)
- for _, item := range items {
- itemMap[item.Id] = item
- }
- roots := make([]*types.DeptItem, 0)
- for _, item := range items {
- if item.ParentId == 0 {
- roots = append(roots, item)
- } else if parent, ok := itemMap[item.ParentId]; ok {
- parent.Children = append(parent.Children, item)
- } else {
- l.Errorf("DeptTree: dept id=%d has parentId=%d which does not exist, treated as root", item.Id, item.ParentId)
- roots = append(roots, item)
- }
- }
- return roots, nil
- }
|