deptTreeLogic.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // DeptTree 部门树。一次性返回完整的组织架构树形结构,用于前端部门选择器和组织架构展示。
  21. func (l *DeptTreeLogic) DeptTree() (resp []*types.DeptItem, err error) {
  22. list, err := l.svcCtx.SysDeptModel.FindAll(l.ctx)
  23. if err != nil {
  24. return nil, err
  25. }
  26. items := make([]*types.DeptItem, 0, len(list))
  27. for _, d := range list {
  28. items = append(items, &types.DeptItem{
  29. Id: d.Id,
  30. ParentId: d.ParentId,
  31. Name: d.Name,
  32. Path: d.Path,
  33. Sort: d.Sort,
  34. DeptType: d.DeptType,
  35. Remark: d.Remark,
  36. Status: d.Status,
  37. CreateTime: d.CreateTime,
  38. Children: make([]*types.DeptItem, 0),
  39. })
  40. }
  41. itemMap := make(map[int64]*types.DeptItem)
  42. for _, item := range items {
  43. itemMap[item.Id] = item
  44. }
  45. roots := make([]*types.DeptItem, 0)
  46. for _, item := range items {
  47. if item.ParentId == 0 {
  48. roots = append(roots, item)
  49. } else if parent, ok := itemMap[item.ParentId]; ok {
  50. parent.Children = append(parent.Children, item)
  51. } else {
  52. l.Errorf("DeptTree: dept id=%d has parentId=%d which does not exist, treated as root", item.Id, item.ParentId)
  53. roots = append(roots, item)
  54. }
  55. }
  56. return roots, nil
  57. }