作者 yangfu

自定义菜单 、 菜单功能

... ... @@ -11,10 +11,12 @@ import (
type ListCompanyCustomizeMenusCommand struct {
// 企业id
CompanyId int64 `cname:"企业id" json:"companyId,string" valid:"Required"`
// 菜单类别 web app
MenuCategory string `json:"menuCategory,omitempty" valid:"Required"`
}
func (listCompanyCustomizeMenusCommand *ListCompanyCustomizeMenusCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (listCompanyCustomizeMenusCommand *ListCompanyCustomizeMenusCommand) ValidateCommand() error {
... ...
... ... @@ -10,11 +10,11 @@ import (
type UpdateCompanyCustomizeMenusCommand struct {
// 企业id
CompanyId int64 `cname:"企业id" json:"companyId,string" valid:"Required"`
CompanyId int64 `cname:"企业id" json:"companyId" valid:"Required"`
// 菜单编号
MenuId int64 `cname:"菜单编号" json:"menuId,string" valid:"Required"`
MenuId int64 `cname:"菜单编号" json:"menuId" valid:"Required"`
// 菜单名称
MenuName string `cname:"菜单名称" json:"menuName" valid:"Required"`
//MenuName string `cname:"菜单名称" json:"menuName" valid:"Required"`
// 菜单别名
MenuAlias string `cname:"菜单别名" json:"menuAlias" valid:"Required"`
// 排序
... ... @@ -22,7 +22,7 @@ type UpdateCompanyCustomizeMenusCommand struct {
}
func (updateCompanyCustomizeMenusCommand *UpdateCompanyCustomizeMenusCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (updateCompanyCustomizeMenusCommand *UpdateCompanyCustomizeMenusCommand) ValidateCommand() error {
... ...
package dto
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/utils"
)
func RetCustomizeMenu(menus []*domain.Menu, customizeMenus []*domain.CustomizeMenu) interface{} {
var ret []interface{}
menusMap := make(map[int64]*domain.Menu)
for i := range menus {
menusMap[menus[i].MenuId] = menus[i]
}
for i := range customizeMenus {
m := customizeMenus[i]
if menu, ok := menusMap[m.MenuId]; ok {
menu.MenuAlias = m.MenuAlias
}
}
for i := range menus {
fieldMenu := utils.LoadCustomFieldToMap(menus[i], "MenuId", "ParentId", "MenuName", "Code", "Icon", "MenuAlias", "MenuType", "Remark", "Sort")
fieldMenu["parentMenuName"] = ""
if menu, ok := menusMap[menus[i].ParentId]; ok {
fieldMenu["parentMenuName"] = menu.MenuName
}
ret = append(ret, fieldMenu)
}
return ret
}
... ...
... ... @@ -5,9 +5,12 @@ import (
"github.com/linmadan/egglib-go/core/application"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/company/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/company/dto"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/company/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/common"
"strconv"
)
// 企业
... ... @@ -123,7 +126,7 @@ func (companyService *CompanyService) ListCompany(listCompanyQuery *query.ListCo
}
}
// 返回自定义菜单列表
// 返回自定义菜单列表(匹配有设置的菜单)
func (companyService *CompanyService) ListCompanyCustomizeMenus(listCompanyCustomizeMenusCommand *command.ListCompanyCustomizeMenusCommand) (interface{}, error) {
if err := listCompanyCustomizeMenusCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
... ... @@ -138,10 +141,41 @@ func (companyService *CompanyService) ListCompanyCustomizeMenus(listCompanyCusto
defer func() {
transactionContext.RollbackTransaction()
}()
var menuRepository domain.MenuRepository
if value, err := factory.CreateMenuRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
menuRepository = value
}
queryOptions := common.SimpleStructToMap(listCompanyCustomizeMenusCommand)
if m, e := menuRepository.FindOne(map[string]interface{}{"code": listCompanyCustomizeMenusCommand.MenuCategory}); e == nil && m != nil {
queryOptions["category"] = strconv.Itoa(int(m.MenuId))
}
_, menus, err := menuRepository.Find(queryOptions)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
var customizeMenuRepository domain.CustomizeMenuRepository
if value, err := factory.CreateCustomizeMenuRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
customizeMenuRepository = value
}
_, customizeMenus, err := customizeMenuRepository.Find(queryOptions)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
ret := dto.RetCustomizeMenu(menus, customizeMenus)
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
return map[string]interface{}{"menus": ret}, nil
}
// 移除企业
... ... @@ -242,10 +276,59 @@ func (companyService *CompanyService) UpdateCompanyCustomizeMenus(updateCompanyC
defer func() {
transactionContext.RollbackTransaction()
}()
var menuRepository domain.MenuRepository
if value, err := factory.CreateMenuRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
menuRepository = value
}
var menuName string
if menu, err := menuRepository.FindOne(map[string]interface{}{"menuId": updateCompanyCustomizeMenusCommand.MenuId}); err != nil || (menu != nil && menu.IsPublish != domain.MenuPublic) {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "菜单不存在")
} else {
menuName = menu.MenuName
}
var customizeMenuRepository domain.CustomizeMenuRepository
if value, err := factory.CreateCustomizeMenuRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
customizeMenuRepository = value
}
customizeMenu, e := customizeMenuRepository.FindOne(map[string]interface{}{
"companyId": updateCompanyCustomizeMenusCommand.CompanyId,
"menuId": updateCompanyCustomizeMenusCommand.MenuId,
"isPublish": domain.MenuPublic,
})
if e == domain.ErrorNotFound {
customizeMenu = &domain.CustomizeMenu{
CompanyId: updateCompanyCustomizeMenusCommand.CompanyId,
MenuId: updateCompanyCustomizeMenusCommand.MenuId,
MenuName: menuName,
MenuAlias: updateCompanyCustomizeMenusCommand.MenuAlias,
Sort: updateCompanyCustomizeMenusCommand.Sort,
}
} else if customizeMenu != nil {
data := tool_funs.SimpleStructToMap(updateCompanyCustomizeMenusCommand)
data["menuName"] = menuName
if err := customizeMenu.Update(data); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
} else {
return nil, application.ThrowError(application.TRANSACTION_ERROR, e.Error())
}
if customizeMenu, err = customizeMenuRepository.Save(customizeMenu); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, e.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
return customizeMenu, nil
}
func NewCompanyService(options map[string]interface{}) *CompanyService {
... ...
... ... @@ -53,3 +53,11 @@ func CreateCompanyRepository(options map[string]interface{}) (domain.CompanyRepo
}
return repository.NewCompanyRepository(transactionContext)
}
func CreateCustomizeMenuRepository(options map[string]interface{}) (domain.CustomizeMenuRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewCustomizeMenuRepository(transactionContext)
}
... ...
... ... @@ -24,9 +24,9 @@ type CreateMenuCommand struct {
// 菜单说明
Desc string `json:"desc,omitempty"`
// 菜单是否公开状态,[0:隐藏],[1:显示],默认显示
IsPublish int `json:"isPublish"`
IsPublish int `json:"isPublish" valid:"Required"`
// 启用状态(启用:1 禁用:2),默认启用
EnableStatus int `json:"enableStatus"`
EnableStatus int `json:"enableStatus" valid:"Required"`
}
func (createMenuCommand *CreateMenuCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -18,11 +18,11 @@ type ListMenuQuery struct {
// 查询偏离量
Offset int `json:"offset"`
// 查询限制
Limit int `json:"limit" valid:"Required"`
Limit int `json:"limit"`
// web分页
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize" valid:"Required"`
PageSize int `json:"pageSize"`
}
func (listMenuQuery *ListMenuQuery) Valid(validation *validation.Validation) {
... ...
... ... @@ -52,7 +52,7 @@ func (menuService *MenuService) CreateMenu(createMenuCommand *command.CreateMenu
menuRepository = value
}
// 1.菜单类型验证
if newMenu.ValidMenuType() {
if !newMenu.ValidMenuType() {
return nil, application.ThrowError(application.ARG_ERROR, domain.ErrorMenuType.Error())
}
// 2.菜单编码验证
... ... @@ -248,8 +248,8 @@ func (menuService *MenuService) UpdateMenu(updateMenuCommand *command.UpdateMenu
}
// 1.验证code是否有重复的情况
if menu.Code != updateMenuCommand.Code {
if m, e := menuRepository.FindOne(map[string]interface{}{"code": updateMenuCommand.Code}); e == nil && m.MenuId != menu.MenuId {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
if m, e := menuRepository.FindOne(map[string]interface{}{"code": updateMenuCommand.Code}); e == nil && m != nil && m.MenuId != menu.MenuId {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, fmt.Sprintf("菜单编码:%v已重复,请重新输入", updateMenuCommand.Code))
}
}
// 2.验证父级节点是否有发生更新
... ...
... ... @@ -7,8 +7,8 @@ var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "123456"
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "5432"
var DISABLE_CREATE_TABLE = true
var DISABLE_SQL_GENERATE_PRINT = true
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
var DISABLE_SQL_GENERATE_COMMENT = true
func init() {
... ...
package domain
// 自定义菜单 (base)(菜单维护)
type CustomizeMenu struct {
// 自定义菜单id
CustomizeMenusId int64 `json:"customizeMenusId,string"`
// 企业id
CompanyId int64 `json:"companyId,string"`
// 菜单id
MenuId int64 `json:"menuId,string"`
// 菜单名称
MenuName string `json:"menuName"`
// 菜单别名
MenuAlias string `json:"menuAlias"`
// 排序
Sort int `json:"sort"`
}
type CustomizeMenuRepository interface {
Save(customizeMenu *CustomizeMenu) (*CustomizeMenu, error)
Remove(customizeMenu *CustomizeMenu) (*CustomizeMenu, error)
FindOne(queryOptions map[string]interface{}) (*CustomizeMenu, error)
Find(queryOptions map[string]interface{}) (int64, []*CustomizeMenu, error)
}
func (customizeMenu *CustomizeMenu) Identify() interface{} {
if customizeMenu.CustomizeMenusId == 0 {
return nil
}
return customizeMenu.CustomizeMenusId
}
func (customizeMenu *CustomizeMenu) Update(data map[string]interface{}) error {
//if companyId, ok := data["companyId"]; ok {
// customizeMenu.CompanyId = companyId.(int64)
//}
//if menuId, ok := data["menuId"]; ok {
// customizeMenu.MenuId = menuId.(int64)
//}
if menuName, ok := data["menuName"]; ok {
customizeMenu.MenuName = menuName.(string)
}
if menuAlias, ok := data["menuAlias"]; ok {
customizeMenu.MenuAlias = menuAlias.(string)
}
if sort, ok := data["sort"]; ok {
customizeMenu.Sort = sort.(int)
}
return nil
}
... ...
package domain
import "fmt"
var (
ErrorNotFound = fmt.Errorf("没有此资源")
)
... ...
... ... @@ -31,6 +31,11 @@ const (
MenuPrivate = 2 // 菜单未公开
)
const (
WebMenuCode = "web"
AppMenuCode = "app"
)
// 菜单类型
type MenuType string
... ... @@ -42,6 +47,8 @@ type Menu struct {
ParentId int64 `json:"parentId,omitempty"`
// 菜单名称
MenuName string `json:"menuName,omitempty"`
// 菜单别名
MenuAlias string `json:"menuAlias,omitempty"`
// 菜单编码 SYSTEM_USER_EDIT / 100101 (字符编码)
Code string `json:"code,omitempty"`
// 权限编码 user:edit
... ...
... ... @@ -30,6 +30,8 @@ func init() {
if !constant.DISABLE_CREATE_TABLE {
for _, model := range []interface{}{
(*models.Menu)(nil),
(*models.CustomizeMenu)(nil),
//(*models.User)(nil),
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
... ...
... ... @@ -8,7 +8,7 @@ import (
type Company struct {
tableName string `pg:"users.company,alias:company" comment:"企业"`
// 企业id
CompanyId int64 `comment:"企业id"`
CompanyId int64 `pg:",pk" comment:"企业id"`
// 企业配置信息
CompanyConfig *domain.CompanyConfig `comment:"企业配置信息"`
// 企业基本信息
... ...
package models
type CustomizeMenu struct {
tableName string `pg:"users.customize_menu" comment:"自定义菜单 (base)(菜单维护)"`
// 自定义菜单id
CustomizeMenuId int64 `pg:",pk" comment:"自定义菜单id"`
// 企业id
CompanyId int64 `comment:"企业id"`
// 菜单id
MenuId int64 `comment:"菜单id"`
// 菜单名称
MenuName string `comment:"菜单名称"`
// 菜单别名
MenuAlias string `comment:"菜单别名"`
// 排序
Sort int `comment:"排序"`
}
... ...
... ... @@ -8,7 +8,7 @@ import (
type Org struct {
tableName string `pg:"users.org,alias:org" comment:"组织"`
// 组织ID
OrgId int64 `comment:"组织ID"`
OrgId int64 `pg:",pk" comment:"组织ID"`
// 企业id
CompanyId int64 `comment:"企业id"`
// 创建时间
... ...
... ... @@ -8,7 +8,7 @@ import (
type Role struct {
tableName string `pg:"users.role,alias:role" comment:"角色"`
// 角色ID
RoleId int64 `comment:"角色ID"`
RoleId int64 `pg:",pk" comment:"角色ID"`
// 企业id
CompanyId int64 `comment:"企业id"`
// 组织ID
... ...
... ... @@ -8,7 +8,7 @@ import (
type User struct {
tableName string `pg:"users.user,alias:user"`
// 用户Id 用户唯一标识
UserId int64 `comment:"用户Id"`
UserId int64 `pg:",pk" comment:"用户Id"`
// 企业id
CompanyId int64 `comment:"企业id"`
// 用户基础数据id
... ...
... ... @@ -8,7 +8,7 @@ import (
type UserBase struct {
tableName string `pg:"users.user_base,alias:user_base" comment:"用户基础"`
// 用户基础数据id
UserBaseId int64 `comment:"用户基础数据id"`
UserBaseId int64 `pg:",pk" comment:"用户基础数据id"`
// 用户信息
UserInfo *domain.UserInfo `comment:"用户信息"`
// 账号
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/models"
)
func TransformToCustomizeMenuDomainModelFromPgModels(customizeMenuModel *models.CustomizeMenu) (*domain.CustomizeMenu, error) {
return &domain.CustomizeMenu{
CustomizeMenusId: customizeMenuModel.CustomizeMenuId,
CompanyId: customizeMenuModel.CompanyId,
MenuId: customizeMenuModel.MenuId,
MenuName: customizeMenuModel.MenuName,
MenuAlias: customizeMenuModel.MenuAlias,
Sort: customizeMenuModel.Sort,
}, nil
}
... ...
... ... @@ -10,6 +10,7 @@ func TransformToMenuDomainModelFromPgModels(menuModel *models.Menu) (*domain.Men
MenuId: menuModel.MenuId,
ParentId: menuModel.ParentId,
MenuName: menuModel.MenuName,
MenuAlias: menuModel.MenuName,
Code: menuModel.Code,
AccessCode: menuModel.AccessCode,
MenuType: menuModel.MenuType,
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg/transform"
)
type CustomizeMenuRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *CustomizeMenuRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *CustomizeMenuRepository) Save(customizeMenu *domain.CustomizeMenu) (*domain.CustomizeMenu, error) {
sqlBuildFields := []string{
"customize_menu_id",
"company_id",
"menu_id",
"menu_name",
"menu_alias",
"sort",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "customize_menu_id"))
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlbuilder.RemoveSqlFields(sqlBuildFields, "customize_menu_id"))
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "customize_menu_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if customizeMenu.Identify() == nil {
if _, err := tx.QueryOne(
pg.Scan(
&customizeMenu.CustomizeMenusId,
&customizeMenu.CompanyId,
&customizeMenu.MenuId,
&customizeMenu.MenuName,
&customizeMenu.MenuAlias,
&customizeMenu.Sort,
),
fmt.Sprintf("INSERT INTO users.customize_menu (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
customizeMenu.CompanyId,
customizeMenu.MenuId,
customizeMenu.MenuName,
customizeMenu.MenuAlias,
customizeMenu.Sort,
); err != nil {
return customizeMenu, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&customizeMenu.CustomizeMenusId,
&customizeMenu.CompanyId,
&customizeMenu.MenuId,
&customizeMenu.MenuName,
&customizeMenu.MenuAlias,
&customizeMenu.Sort,
),
fmt.Sprintf("UPDATE users.customize_menu SET %s WHERE customize_menu_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
customizeMenu.CompanyId,
customizeMenu.MenuId,
customizeMenu.MenuName,
customizeMenu.MenuAlias,
customizeMenu.Sort,
customizeMenu.Identify(),
); err != nil {
return customizeMenu, err
}
}
return customizeMenu, nil
}
func (repository *CustomizeMenuRepository) Remove(customizeMenu *domain.CustomizeMenu) (*domain.CustomizeMenu, error) {
tx := repository.transactionContext.PgTx
customizeMenuModel := new(models.CustomizeMenu)
customizeMenuModel.CustomizeMenuId = customizeMenu.Identify().(int64)
if _, err := tx.Model(customizeMenuModel).WherePK().Delete(); err != nil {
return customizeMenu, err
}
return customizeMenu, nil
}
func (repository *CustomizeMenuRepository) FindOne(queryOptions map[string]interface{}) (*domain.CustomizeMenu, error) {
tx := repository.transactionContext.PgTx
customizeMenuModel := new(models.CustomizeMenu)
query := sqlbuilder.BuildQuery(tx.Model(customizeMenuModel), queryOptions)
query.SetWhereByQueryOption("customize_menu_id = ?", "customizeMenuId")
query.SetWhereByQueryOption("menu_id = ?", "menuId")
query.SetWhereByQueryOption("company_id = ?", "companyId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, domain.ErrorNotFound
} else {
return nil, err
}
}
if customizeMenuModel.CustomizeMenuId == 0 {
return nil, nil
} else {
return transform.TransformToCustomizeMenuDomainModelFromPgModels(customizeMenuModel)
}
}
func (repository *CustomizeMenuRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.CustomizeMenu, error) {
tx := repository.transactionContext.PgTx
var customizeMenuModels []*models.CustomizeMenu
customizeMenus := make([]*domain.CustomizeMenu, 0)
query := sqlbuilder.BuildQuery(tx.Model(&customizeMenuModels), queryOptions)
query.SetWhereByQueryOption("company_id =?", "companyId")
query.SetOrderDirect("customize_menu_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, customizeMenus, err
} else {
for _, customizeMenuModel := range customizeMenuModels {
if customizeMenu, err := transform.TransformToCustomizeMenuDomainModelFromPgModels(customizeMenuModel); err != nil {
return 0, customizeMenus, err
} else {
customizeMenus = append(customizeMenus, customizeMenu)
}
}
return int64(count), customizeMenus, nil
}
}
func NewCustomizeMenuRepository(transactionContext *pgTransaction.TransactionContext) (*CustomizeMenuRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CustomizeMenuRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -69,7 +69,7 @@ func (repository *MenuRepository) Save(menu *domain.Menu) (*domain.Menu, error)
&menu.IsPublish,
&menu.EnableStatus,
),
fmt.Sprintf("INSERT INTO user.menu (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
fmt.Sprintf(`INSERT INTO users.menu (%s) VALUES (%s) RETURNING %s`, insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
menu.ParentId,
menu.MenuName,
menu.Code,
... ... @@ -102,7 +102,7 @@ func (repository *MenuRepository) Save(menu *domain.Menu) (*domain.Menu, error)
&menu.IsPublish,
&menu.EnableStatus,
),
fmt.Sprintf("UPDATE user.menu SET %s WHERE menu_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
fmt.Sprintf("UPDATE users.menu SET %s WHERE menu_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
menu.ParentId,
menu.MenuName,
menu.Code,
... ... @@ -164,8 +164,10 @@ func (repository *MenuRepository) Find(queryOptions map[string]interface{}) (int
query.Where(fmt.Sprintf("menu_name like '%%%v%%'", v))
}
query.SetWhereByQueryOption("parent_id = ?", "parentId")
query.SetWhereByQueryOption("is_publish =?", "isPublish")
query.SetOffsetAndLimit(20)
query.SetOrderDirect("menu_id", "asc")
query.SetOrderDirect("parent_id", "asc")
query.SetOrderDirect("sort", "asc")
if count, err := query.SelectAndCount(); err != nil {
return 0, menus, err
} else {
... ...
package utils
import (
"bytes"
"encoding/json"
"fmt"
jsonlib "github.com/linmadan/egglib-go/utils/json"
"io"
"reflect"
"strconv"
"strings"
"time"
)
func CamelCase(name string, firstUpper bool) string {
array := []byte(name)
if len(array) == 0 {
return ""
}
rspArray := make([]byte, len(array))
if firstUpper {
copy(rspArray[:1], strings.ToUpper(string(array[:1])))
} else {
copy(rspArray[:1], strings.ToLower(string(array[:1])))
}
copy(rspArray[1:], array[1:])
return string(rspArray)
}
func ObjectToMap(o interface{}) map[string]interface{} {
if o == nil {
return nil
}
value := reflect.ValueOf(o)
if value.Kind() != reflect.Ptr {
return nil
}
elem := value.Elem()
relType := elem.Type()
m := make(map[string]interface{})
for i := 0; i < relType.NumField(); i++ {
field := relType.Field(i)
if elem.Field(i).IsZero() {
continue
}
m[CamelCase(field.Name, false)] = elem.Field(i).Interface()
}
return m
}
// AssertString convert v to string value
func AssertString(v interface{}) string {
if v == nil {
return ""
}
// if func (v *Type) String() string, we can't use Elem()
switch vt := v.(type) {
case fmt.Stringer:
return vt.String()
}
val := reflect.ValueOf(v)
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = val.Elem()
}
switch vt := val.Interface().(type) {
case bool:
return strconv.FormatBool(vt)
case error:
return vt.Error()
case float32:
return strconv.FormatFloat(float64(vt), 'f', -1, 32)
case float64:
return strconv.FormatFloat(vt, 'f', -1, 64)
case fmt.Stringer:
return vt.String()
case int:
return strconv.Itoa(vt)
case int8:
return strconv.Itoa(int(vt))
case int16:
return strconv.Itoa(int(vt))
case int32:
return strconv.Itoa(int(vt))
case int64:
return strconv.FormatInt(vt, 10)
case string:
return vt
case uint:
return strconv.FormatUint(uint64(vt), 10)
case uint8:
return strconv.FormatUint(uint64(vt), 10)
case uint16:
return strconv.FormatUint(uint64(vt), 10)
case uint32:
return strconv.FormatUint(uint64(vt), 10)
case uint64:
return strconv.FormatUint(vt, 10)
case []byte:
return string(vt)
default:
return fmt.Sprint(val.Interface())
}
}
// ValidatePtr validate v is a ptr value
func ValidatePtr(v *reflect.Value) error {
// sequence is very important, IsNil must be called after checking Kind() with reflect.Ptr,
// panic otherwise
if !v.IsValid() || v.Kind() != reflect.Ptr || v.IsNil() {
return fmt.Errorf("not a valid pointer: %v", v)
}
return nil
}
func LoadCustomFieldToMap(src interface{}, fields ...string) map[string]interface{} {
rsp := LoadCustomField(src, fields...)
if rsp == nil {
return map[string]interface{}{}
}
return rsp.(map[string]interface{})
}
func LoadCustomField(src interface{}, fields ...string) interface{} {
typeSrc := reflect.TypeOf(src)
valueSrc := reflect.ValueOf(src)
if v, ok := src.(reflect.Value); ok {
valueSrc = v
typeSrc = v.Type()
}
if typeSrc.Kind() == reflect.Ptr {
valueSrc = valueSrc.Elem()
}
k := valueSrc.Kind()
switch k {
case reflect.Array, reflect.Slice:
len := valueSrc.Len()
retSliceMap := make([]map[string]interface{}, 0)
if len == 0 {
return retSliceMap
}
for i := 0; i < len; i++ {
v := valueSrc.Index(i)
retSliceMap = append(retSliceMap, (LoadCustomField(v, fields...)).(map[string]interface{}))
}
return retSliceMap
case reflect.Struct:
retSliceMap := make(map[string]interface{})
for _, filed := range fields {
f := valueSrc.FieldByName(filed)
if !f.IsValid() {
continue
}
v := f.Interface()
if t, ok := v.(time.Time); ok {
v = t.Local().Format("2006-01-02 15:04:05")
}
retSliceMap[CamelCase(filed, false)] = v
}
return retSliceMap
default:
return src
}
return src
}
func AppendCustomField(src interface{}, options map[string]interface{}) interface{} {
var mapSrc map[string]interface{}
var ok bool
mapSrc, ok = src.(map[string]interface{})
if !ok {
jsonlib.Unmarshal([]byte(jsonlib.MarshalToString(src)), &mapSrc)
}
for field, value := range options {
mapSrc[CamelCase(field, false)] = value
}
return mapSrc
}
/*
json 格式化
*/
func Marshal(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func Unmarshal(data []byte, v interface{}) error {
decoder := json.NewDecoder(bytes.NewReader(data))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(string(data), err)
}
return nil
}
func UnmarshalFromString(str string, v interface{}) error {
decoder := json.NewDecoder(strings.NewReader(str))
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(str, err)
}
return nil
}
func UnmarshalFromReader(reader io.Reader, v interface{}) error {
var buf strings.Builder
teeReader := io.TeeReader(reader, &buf)
decoder := json.NewDecoder(teeReader)
if err := unmarshalUseNumber(decoder, v); err != nil {
return formatError(buf.String(), err)
}
return nil
}
func unmarshalUseNumber(decoder *json.Decoder, v interface{}) error {
decoder.UseNumber()
return decoder.Decode(v)
}
func formatError(v string, err error) error {
return fmt.Errorf("string: `%s`, error: `%s`", v, err.Error())
}
type ReflectVal struct {
T reflect.Type
V reflect.Value
}
/*
拷贝当前对象到目标对象,具有相同属性的值
*/
func CopyObject(src, dst interface{}) {
var srcMap = make(map[string]ReflectVal)
vs := reflect.ValueOf(src)
ts := reflect.TypeOf(src)
vd := reflect.ValueOf(dst)
td := reflect.TypeOf(dst)
ls := vs.Elem().NumField()
for i := 0; i < ls; i++ {
srcMap[ts.Elem().Field(i).Name] = ReflectVal{
T: vs.Elem().Field(i).Type(),
V: vs.Elem().Field(i),
}
}
ld := vd.Elem().NumField()
for i := 0; i < ld; i++ {
n := td.Elem().Field(i).Name
t := vd.Elem().Field(i).Type()
if v, ok := srcMap[n]; ok && v.T == t && vd.Elem().Field(i).CanSet() {
vd.Elem().Field(i).Set(v.V)
}
}
}
... ...
... ... @@ -74,3 +74,21 @@ func (controller *CompanyController) UpdateCompanyCustomizeMenus() {
data, err := companyService.UpdateCompanyCustomizeMenus(updateCompanyCustomizeMenusCommand)
controller.Response(data, err)
}
func (controller *CompanyController) SearchCompanyCustomizeMenus() {
companyService := service.NewCompanyService(nil)
listCompanyCustomizeMenusCommand := &command.ListCompanyCustomizeMenusCommand{}
controller.Unmarshal(listCompanyCustomizeMenusCommand)
listCompanyCustomizeMenusCommand.CompanyId = 1
data, err := companyService.ListCompanyCustomizeMenus(listCompanyCustomizeMenusCommand)
controller.Response(data, err)
}
func (controller *CompanyController) AdapterUpdateCompanyCustomizeMenus() {
companyService := service.NewCompanyService(nil)
updateCompanyCustomizeMenusCommand := &command.UpdateCompanyCustomizeMenusCommand{}
controller.Unmarshal(updateCompanyCustomizeMenusCommand)
updateCompanyCustomizeMenusCommand.CompanyId = 1
data, err := companyService.UpdateCompanyCustomizeMenus(updateCompanyCustomizeMenusCommand)
controller.Response(data, err)
}
... ...
... ... @@ -13,4 +13,8 @@ func init() {
web.Router("/company/search", &controllers.CompanyController{}, "Post:ListCompany")
web.Router("/company/:companyId/customize-menus/", &controllers.CompanyController{}, "Get:ListCompanyCustomizeMenus")
web.Router("/company/:companyId/customize-menus", &controllers.CompanyController{}, "Put:UpdateCompanyCustomizeMenus")
// 适配web
web.Router("/v1/web/menus/search", &controllers.CompanyController{}, "Post:SearchCompanyCustomizeMenus")
web.Router("/v1/web/menus", &controllers.CompanyController{}, "Put:AdapterUpdateCompanyCustomizeMenus")
}
... ...
... ... @@ -10,15 +10,15 @@ func init() {
web.Router("/menus/:menuId", &controllers.MenuController{}, "Put:UpdateMenu")
web.Router("/menus/:menuId", &controllers.MenuController{}, "Get:GetMenu")
web.Router("/menus/:menuId", &controllers.MenuController{}, "Delete:RemoveMenu")
web.Router("/menus/search", &controllers.MenuController{}, "Get:ListMenu")
web.Router("/menus/", &controllers.MenuController{}, "Get:ListMenu")
web.Router("/menus/search", &controllers.MenuController{}, "Post:SearchMenu")
web.Router("/v1/web/menus/", &controllers.MenuController{}, "Post:CreateMenu")
web.Router("/v1/web/menus/:menuId", &controllers.MenuController{}, "Put:UpdateMenu")
web.Router("/v1/web/menus/:menuId", &controllers.MenuController{}, "Get:GetMenu")
web.Router("/v1/web/menus/:menuId", &controllers.MenuController{}, "Delete:RemoveMenu")
web.Router("/v1/web/menus/search", &controllers.MenuController{}, "Get:ListMenu")
web.Router("/v1/web/menus/search", &controllers.MenuController{}, "Post:SearchMenu")
web.Router("/v1/opt/menus/", &controllers.MenuController{}, "Post:CreateMenu")
web.Router("/v1/opt/menus/:menuId", &controllers.MenuController{}, "Put:UpdateMenu")
web.Router("/v1/opt/menus/:menuId", &controllers.MenuController{}, "Get:GetMenu")
web.Router("/v1/opt/menus/:menuId", &controllers.MenuController{}, "Delete:RemoveMenu")
web.Router("/v1/opt/menus/search", &controllers.MenuController{}, "Get:ListMenu")
web.Router("/v1/opt/menus/search", &controllers.MenuController{}, "Post:SearchMenu")
web.Router("/v1/web/common/dictionary/search", &controllers.CommonController{}, "Post:DictionarySearch")
}
... ...