package menu import ( "slices" "strings" "wechat-robot/internal/database" "wechat-robot/model/vo/menu" "wechat-robot/pkg/types" "wechat-robot/service/role" ) type menuRecordItem struct { Id string Type types.MenuType Name string Path string Icon string Sort int ParentId *string RoleCode string AuthCode string } // GetUserMenus // @description: 获取用户权限内的菜单列表 // @param userId string 用户Id // @return records []entity.Menu 菜单列表 // @return err error 错误信息 func GetUserMenus(userId string) (records []menu.Item, err error) { // 检查是否是超级管理员用户 isSuperAdminUser := role.CheckIsSuperAdminUser(userId) // 取出用户包含的所有菜单 var menus []menuRecordItem tx := database.Client.Table("t_menu AS tm"). Joins("LEFT JOIN t_role_menu AS trm ON trm.menu_id = tm.id"). Joins("LEFT JOIN t_role AS tr ON tr.id = trm.role_id AND tr.is_del IS FALSE"). Select("tm.*", "tr.code AS role_code"). Where("tm.is_del IS FALSE") if !isSuperAdminUser { // 不是超级管理员,只能获取自己的菜单 tx.Joins("LEFT JOIN t_admin_user_role AS tur ON tur.role_id = tr.id"). Where("tur.user_id = ?", userId) } err = tx.Find(&menus).Error if err != nil { return } // 处理出菜单Id对应的角色代码,然后去重 var items []menuRecordItem roleCodesMap := make(map[string][]string) // key: menuId, value: roleCode Array authMap := make(map[string][]string) // key: menuId, value: 类型为按钮的path for _, m := range menus { if _, ok := roleCodesMap[m.Id]; !ok { if m.RoleCode != "" { roleCodesMap[m.Id] = []string{m.RoleCode} } // 将菜单填充到items里 if m.Type == types.MenuTypeMenu { items = append(items, m) } } else { roleCodesMap[m.Id] = append(roleCodesMap[m.Id], m.RoleCode) } // 如果是按钮,且有父级,就把按钮的path放到父级的authMap里 if m.Type == types.MenuTypeButton && m.ParentId != nil { authMap[*m.ParentId] = append(authMap[*m.ParentId], m.Path) } } // 再次循环数据,把角色代码们拼接起来 for i, m := range items { roleCodes := roleCodesMap[m.Id] authCodes := authMap[m.Id] if isSuperAdminUser { // 固定填充一个admin角色代码进去 roleCodes = append(roleCodes, "admin") } items[i].RoleCode = strings.Join(slices.Compact(roleCodes), ",") items[i].AuthCode = strings.Join(slices.Compact(authCodes), ",") } // 处理成树形结构 records = toTree(items, "") return }