deptTreeLogic.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package dept
  2. import (
  3. "context"
  4. "perms-system-server/internal/svc"
  5. "perms-system-server/internal/types"
  6. "github.com/zeromicro/go-zero/core/logx"
  7. )
  8. type DeptTreeLogic struct {
  9. logx.Logger
  10. ctx context.Context
  11. svcCtx *svc.ServiceContext
  12. }
  13. func NewDeptTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeptTreeLogic {
  14. return &DeptTreeLogic{
  15. Logger: logx.WithContext(ctx),
  16. ctx: ctx,
  17. svcCtx: svcCtx,
  18. }
  19. }
  20. func (l *DeptTreeLogic) DeptTree() (resp []*types.DeptItem, err error) {
  21. list, err := l.svcCtx.SysDeptModel.FindAll(l.ctx)
  22. if err != nil {
  23. return nil, err
  24. }
  25. items := make([]*types.DeptItem, 0, len(list))
  26. for _, d := range list {
  27. items = append(items, &types.DeptItem{
  28. Id: d.Id,
  29. ParentId: d.ParentId,
  30. Name: d.Name,
  31. Path: d.Path,
  32. Sort: d.Sort,
  33. DeptType: d.DeptType,
  34. Remark: d.Remark,
  35. Status: d.Status,
  36. CreateTime: d.CreateTime,
  37. Children: make([]*types.DeptItem, 0),
  38. })
  39. }
  40. itemMap := make(map[int64]*types.DeptItem)
  41. for _, item := range items {
  42. itemMap[item.Id] = item
  43. }
  44. roots := make([]*types.DeptItem, 0)
  45. for _, item := range items {
  46. if item.ParentId == 0 {
  47. roots = append(roots, item)
  48. } else if parent, ok := itemMap[item.ParentId]; ok {
  49. parent.Children = append(parent.Children, item)
  50. } else {
  51. roots = append(roots, item)
  52. }
  53. }
  54. return roots, nil
  55. }