作者 yangfu

菜单批量 启用、禁用/删除

package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type BatchDeleteMenuCommand struct {
// 菜单ID列表
MenuIds []int64 `cname:"菜单ID列表" json:"menuIds,omitempty"`
}
func (batchDeleteMenuCommand *BatchDeleteMenuCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (batchDeleteMenuCommand *BatchDeleteMenuCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchDeleteMenuCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchDeleteMenuCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
package command
import (
"fmt"
"reflect"
"strings"
"github.com/beego/beego/v2/core/validation"
)
type BatchEnableMenuCommand struct {
// 菜单ID列表
MenuIds []int64 `cname:"菜单ID列表" json:"menuIds,omitempty"`
// 菜单状态
Status int `cname:"菜单状态" json:"status,omitempty"`
}
func (batchEnableMenuCommand *BatchEnableMenuCommand) Valid(validation *validation.Validation) {
//validation.SetError("CustomValid", "未实现的自定义认证")
}
func (batchEnableMenuCommand *BatchEnableMenuCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(batchEnableMenuCommand)
if err != nil {
return err
}
if !b {
elem := reflect.TypeOf(batchEnableMenuCommand).Elem()
for _, validErr := range valid.Errors {
field, isExist := elem.FieldByName(validErr.Field)
if isExist {
return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
} else {
return fmt.Errorf(validErr.Message)
}
}
}
return nil
}
... ...
... ... @@ -26,7 +26,7 @@ type CreateMenuCommand struct {
// 菜单是否公开状态,[0:隐藏],[1:显示],默认显示
IsPublish int `json:"isPublish" valid:"Required"`
// 启用状态(启用:1 禁用:2),默认启用
EnableStatus int `json:"enableStatus" valid:"Required"`
EnableStatus int `json:"enableStatus" `
}
func (createMenuCommand *CreateMenuCommand) Valid(validation *validation.Validation) {
... ...
... ... @@ -41,7 +41,7 @@ func (menuService *MenuService) CreateMenu(createMenuCommand *command.CreateMenu
Sort: createMenuCommand.Sort,
Remark: createMenuCommand.Desc,
IsPublish: createMenuCommand.IsPublish,
EnableStatus: createMenuCommand.EnableStatus,
EnableStatus: domain.MenuStatusDisable,
}
var menuRepository domain.MenuRepository
if value, err := factory.CreateMenuRepository(map[string]interface{}{
... ... @@ -292,6 +292,81 @@ func (menuService *MenuService) UpdateMenu(updateMenuCommand *command.UpdateMenu
}
}
// 批量删除菜单
func (menuService *MenuService) BatchDeleteMenu(batchDeleteMenu *command.BatchDeleteMenuCommand) (interface{}, error) {
if err := batchDeleteMenu.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
menuRepository, _, err := factory.FastPgMenu(transactionContext, 0)
if err != nil {
return nil, err
}
for i := 0; i < len(batchDeleteMenu.MenuIds); i++ {
if menu, err := menuRepository.FindOne(map[string]interface{}{"menuId": batchDeleteMenu.MenuIds[i]}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if _, err := menuRepository.Remove(menu); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
// 批量删除菜单
func (menuService *MenuService) BatchEnableMenu(batchEnableMenu *command.BatchEnableMenuCommand) (interface{}, error) {
if err := batchEnableMenu.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.Error())
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
menuRepository, _, err := factory.FastPgMenu(transactionContext, 0)
if err != nil {
return nil, err
}
for i := 0; i < len(batchEnableMenu.MenuIds); i++ {
if menu, err := menuRepository.FindOne(map[string]interface{}{"menuId": batchEnableMenu.MenuIds[i]}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
} else {
if err := menu.SetPublic(batchEnableMenu.Status); err != nil {
return nil, application.ThrowError(application.BUSINESS_ERROR, err.Error())
}
if _, err := menuRepository.Save(menu); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
}
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return struct{}{}, nil
}
func NewMenuService(options map[string]interface{}) *MenuService {
newMenuService := &MenuService{}
return newMenuService
... ...
... ... @@ -27,6 +27,8 @@ type ListUserQuery struct {
DepName string `cname:"部门名称" json:"depName,omitempty"`
// 手机号码
Phone string `cname:"手机号码" json:"phone,omitempty"`
// 用户类型
UserType int `cname:"用户类型 1:普通用户 2:共创用户 1024:企业注册用户" json:"userType,omitempty"`
// 实时拉取数据 (获取最新的)
PullRealTime bool `cname:"拉取最新数据" json:"pullRealTime,omitempty"`
}
... ...
... ... @@ -151,6 +151,14 @@ func (menu *Menu) ValidMenuType() bool {
return false
}
func (menu *Menu) SetPublic(status int) error {
if !(status == MenuPublic || status == MenuPrivate) {
return fmt.Errorf("非法的公开状态: %v", status)
}
menu.IsPublish = status
return nil
}
/***** 1.实现树 *****/
/*1.1 实现树的方法*/
// GetParentPath 获取菜单路径
... ...
... ... @@ -28,4 +28,6 @@ type Menu struct {
IsPublish int `comment:"菜单是否公开状态,[2:隐藏],[1:显示],默认显示"`
// 启用状态(启用:1 禁用:2),默认启用
EnableStatus int `comment:"启用状态(启用:1 禁用:2),默认启用"`
// 删除时间
//DeletedAt time.Time `comment:"删除时间"`
}
... ...
... ... @@ -196,6 +196,7 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
query.SetWhereByQueryOption("company_id=?", "companyId")
query.SetWhereByQueryOption("organization_id=?", "organizationId")
query.SetWhereByQueryOption("user_base_id=?", "userBaseId")
query.SetWhereByQueryOption("(user_type & ?)>0", "userType")
if v, ok := queryOptions["depName"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`ext->>'depName' like '%%%v%%'`, v))
}
... ... @@ -203,7 +204,7 @@ func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int
query.Where(fmt.Sprintf(`ext->>'userName' like '%%%v%%'`, v))
}
if v, ok := queryOptions["cooperationCompany"]; ok && len(v.(string)) > 0 {
query.Where(fmt.Sprintf(`cooperation_info->>'cooperationCompany'' like '%%%v%%'`, v))
query.Where(fmt.Sprintf(`cooperation_info->>'cooperationCompany' like '%%%v%%'`, v))
}
query.SetOffsetAndLimit(999)
query.SetOrderDirect("user_id", "DESC")
... ...
... ... @@ -72,3 +72,19 @@ func (controller *MenuController) SearchMenu() {
data, err := menuService.ListMenu(listMenuQuery)
controller.Response(data, err)
}
func (controller *MenuController) BatchDeleteMenu() {
menuService := service.NewMenuService(nil)
batchDeleteMenuCommand := &command.BatchDeleteMenuCommand{}
controller.Unmarshal(batchDeleteMenuCommand)
data, err := menuService.BatchDeleteMenu(batchDeleteMenuCommand)
controller.Response(data, err)
}
func (controller *MenuController) BatchEnableMenu() {
menuService := service.NewMenuService(nil)
batchEnableMenu := &command.BatchEnableMenuCommand{}
controller.Unmarshal(batchEnableMenu)
data, err := menuService.BatchEnableMenu(batchEnableMenu)
controller.Response(data, err)
}
... ...
... ... @@ -12,6 +12,8 @@ func init() {
web.Router("/menus/:menuId", &controllers.MenuController{}, "Delete:RemoveMenu")
web.Router("/menus/", &controllers.MenuController{}, "Get:ListMenu")
web.Router("/menus/search", &controllers.MenuController{}, "Post:SearchMenu")
web.Router("/menus/batch-delete", &controllers.MenuController{}, "Post:BatchDeleteMenu")
web.Router("/menus/batch-enable", &controllers.MenuController{}, "Post:BatchEnableMenu")
web.Router("/v1/web/menus/", &controllers.MenuController{}, "Post:CreateMenu")
web.Router("/v1/web/menus/:menuId", &controllers.MenuController{}, "Put:UpdateMenu")
... ... @@ -19,6 +21,8 @@ func init() {
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/web/menus/batch-delete", &controllers.MenuController{}, "Post:BatchDeleteMenu")
web.Router("/v1/web/menus/batch-enable", &controllers.MenuController{}, "Post:BatchEnableMenu")
web.Router("/v1/web/common/dictionary/search", &controllers.CommonController{}, "Post:DictionarySearch")
}
... ...
package menu
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg"
)
var _ = Describe("批量删除菜单", func() {
var menuId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&menuId),
"INSERT INTO menus (menu_id, parent_id, menu_name, code, access_code, menu_type, icon, sort, remark, category, parent_path, enable_status, is_publish) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING menu_id",
"testMenuId", "testParentId", "testMenuName", "testCode", "testAccessCode", "testMenuType", "testIcon", "testSort", "testRemark", "testCategory", "testParentPath", "testEnableStatus", "testIsPublish")
Expect(err).NotTo(HaveOccurred())
})
Describe("批量删除菜单", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"menuIds": "array",
}
httpExpect.POST("/menu/batch-delete").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM menus WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package menu
import (
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/infrastructure/pg"
)
var _ = Describe("批量启用菜单", func() {
var menuId int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&menuId),
"INSERT INTO menus (menu_id, parent_id, menu_name, code, access_code, menu_type, icon, sort, remark, category, parent_path, enable_status, is_publish) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING menu_id",
"testMenuId", "testParentId", "testMenuName", "testCode", "testAccessCode", "testMenuType", "testIcon", "testSort", "testRemark", "testCategory", "testParentPath", "testEnableStatus", "testIsPublish")
Expect(err).NotTo(HaveOccurred())
})
Describe("批量启用菜单", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"menuIds": "array",
"status": "int",
}
httpExpect.POST("/menu/batch-enable").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM menus WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...