admin_menu.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package service
  2. import (
  3. "context"
  4. "gadmin/config"
  5. "gadmin/internal/admin/forms"
  6. "gadmin/internal/gorm/model"
  7. "gadmin/internal/gorm/query"
  8. "github.com/sirupsen/logrus"
  9. "os"
  10. "sort"
  11. )
  12. var Menu = NewAMenu()
  13. type aMenu struct{}
  14. func NewAMenu() *aMenu {
  15. return &aMenu{}
  16. }
  17. func (s *aMenu) GetMenuList() ([]*forms.Menu, error) {
  18. q := query.Use(config.DB).AdminMenu
  19. m := q.WithContext(context.Background())
  20. m = m.Where(q.Disable.Eq(0)).Order(q.Sort)
  21. if os.Getenv("ADMIN_IS_LOCAL") != "1" {
  22. m = m.Where(q.LocalShow.Eq(0))
  23. }
  24. menus, err := m.Find()
  25. if err != nil {
  26. logrus.Error(err)
  27. return nil, err
  28. }
  29. retMenus := handleMenus(menus)
  30. return retMenus, nil
  31. }
  32. func handleMenus(menus []*model.AdminMenu) []*forms.Menu {
  33. menuMap := make(map[int32]*forms.Menu, 0)
  34. for _, menu := range menus {
  35. item := &forms.Menu{
  36. Id: menu.ID,
  37. Component: menu.Component,
  38. Meta: &forms.MenuMeta{
  39. Icon: menu.Icon,
  40. Sort: menu.Sort,
  41. Title: menu.Title,
  42. Hidden: menu.Hidden == 1,
  43. ActiveMenu: menu.ActiveMenu,
  44. IsRoot: menu.IsRoot == 1,
  45. },
  46. Name: menu.Name,
  47. Path: menu.Path,
  48. Redirect: menu.Redirect,
  49. Children: []*forms.Menu{},
  50. }
  51. if menu.ParentID == 0 {
  52. if _, ok := menuMap[menu.ID]; ok {
  53. menuMap[menu.ID].Id = menu.ID
  54. menuMap[menu.ID].Component = menu.Component
  55. menuMap[menu.ID].Meta = item.Meta
  56. menuMap[menu.ID].Name = menu.Name
  57. menuMap[menu.ID].Path = menu.Path
  58. menuMap[menu.ID].Redirect = menu.Redirect
  59. } else {
  60. menuMap[menu.ID] = item
  61. }
  62. } else {
  63. if _, ok := menuMap[menu.ParentID]; ok {
  64. menuMap[menu.ParentID].Children = append(menuMap[menu.ParentID].Children, item)
  65. } else {
  66. menuMap[menu.ParentID] = &forms.Menu{
  67. Id: menu.ParentID,
  68. Meta: &forms.MenuMeta{},
  69. Children: []*forms.Menu{
  70. item,
  71. },
  72. }
  73. }
  74. }
  75. }
  76. retMenus := make([]*forms.Menu, 0, len(menuMap))
  77. for _, menu := range menuMap {
  78. retMenus = append(retMenus, menu)
  79. }
  80. sort.Slice(retMenus, func(i, j int) bool {
  81. return retMenus[i].Meta.Sort < retMenus[j].Meta.Sort
  82. })
  83. return retMenus
  84. }