fix top menu embeding struct
This commit is contained in:
@@ -98,40 +98,37 @@ func (a ByPosition) Len() int { return len(a) }
|
||||
func (a ByPosition) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a ByPosition) Less(i, j int) bool { return a[i].Position < a[j].Position }
|
||||
|
||||
func (s *MenuService) GetTopMenu(id uint) ([]model.B2BTopMenu, error) {
|
||||
func (s *MenuService) GetTopMenu(id uint) ([]*model.B2BTopMenu, error) {
|
||||
items, err := s.routesRepo.GetTopMenu(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
return []model.B2BTopMenu{}, nil
|
||||
}
|
||||
menuMap := make(map[int]*model.B2BTopMenu, len(items))
|
||||
roots := make([]*model.B2BTopMenu, 0)
|
||||
|
||||
// Build a map with empty children slices
|
||||
itemMap := make(map[int]model.B2BTopMenu, len(items))
|
||||
for i := range items {
|
||||
items[i].Children = []model.B2BTopMenu{}
|
||||
itemMap[items[i].MenuID] = items[i]
|
||||
menu := &items[i]
|
||||
menu.Children = make([]*model.B2BTopMenu, 0)
|
||||
menuMap[menu.MenuID] = menu
|
||||
}
|
||||
|
||||
// Build the tree
|
||||
var roots []model.B2BTopMenu
|
||||
for _, item := range itemMap {
|
||||
if item.ParentID == nil || *item.ParentID == 0 {
|
||||
roots = append(roots, itemMap[item.MenuID])
|
||||
} else {
|
||||
parentID := *item.ParentID
|
||||
if parent, exists := itemMap[parentID]; exists {
|
||||
parent.Children = append(parent.Children, item)
|
||||
itemMap[parentID] = parent
|
||||
}
|
||||
for i := range items {
|
||||
menu := &items[i]
|
||||
|
||||
if menu.ParentID == nil {
|
||||
roots = append(roots, menu)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
// Update roots with children
|
||||
for i := range roots {
|
||||
roots[i] = itemMap[roots[i].MenuID]
|
||||
parent, ok := menuMap[*menu.ParentID]
|
||||
if !ok {
|
||||
// fallback for orphaned nodes
|
||||
roots = append(roots, menu)
|
||||
continue
|
||||
}
|
||||
|
||||
parent.Children = append(parent.Children, menu)
|
||||
}
|
||||
|
||||
return roots, nil
|
||||
|
||||
Reference in New Issue
Block a user