github.com/kotovmak/go-admin@v1.1.1/plugins/admin/controller/menu.go (about)

     1  package controller
     2  
     3  import (
     4  	"encoding/json"
     5  	template2 "html/template"
     6  	"net/url"
     7  
     8  	"github.com/kotovmak/go-admin/context"
     9  	"github.com/kotovmak/go-admin/modules/auth"
    10  	"github.com/kotovmak/go-admin/modules/db"
    11  	"github.com/kotovmak/go-admin/modules/errors"
    12  	"github.com/kotovmak/go-admin/modules/language"
    13  	"github.com/kotovmak/go-admin/modules/menu"
    14  	"github.com/kotovmak/go-admin/plugins/admin/models"
    15  	"github.com/kotovmak/go-admin/plugins/admin/modules/constant"
    16  	form2 "github.com/kotovmak/go-admin/plugins/admin/modules/form"
    17  	"github.com/kotovmak/go-admin/plugins/admin/modules/guard"
    18  	"github.com/kotovmak/go-admin/plugins/admin/modules/parameter"
    19  	"github.com/kotovmak/go-admin/plugins/admin/modules/response"
    20  	"github.com/kotovmak/go-admin/plugins/admin/modules/table"
    21  	"github.com/kotovmak/go-admin/template"
    22  	"github.com/kotovmak/go-admin/template/types"
    23  )
    24  
    25  // ShowMenu show menu info page.
    26  func (h *Handler) ShowMenu(ctx *context.Context) {
    27  	h.getMenuInfoPanel(ctx, "", "")
    28  }
    29  
    30  // ShowNewMenu show new menu page.
    31  func (h *Handler) ShowNewMenu(ctx *context.Context) {
    32  	h.showNewMenu(ctx, nil)
    33  }
    34  
    35  func getPlugNameFromReferer(ctx *context.Context) string {
    36  	plugName := ""
    37  	if ref := ctx.Referer(); ref != "" {
    38  		if u, err := url.Parse(ref); err == nil && u != nil {
    39  			plugName = u.Query().Get("__plugin_name")
    40  		}
    41  	}
    42  	return plugName
    43  }
    44  
    45  func getMenuPlugNameParams(plugName string) string {
    46  	params := ""
    47  	if plugName != "" {
    48  		params = "?__plugin_name=" + plugName
    49  	}
    50  	return params
    51  }
    52  
    53  func (h *Handler) showNewMenu(ctx *context.Context, err error) {
    54  
    55  	var (
    56  		alert template2.HTML
    57  
    58  		panel    = h.table("menu", ctx)
    59  		formInfo = panel.GetNewFormInfo()
    60  		user     = auth.Auth(ctx)
    61  		plugName = getPlugNameFromReferer(ctx)
    62  	)
    63  
    64  	if err != nil {
    65  		alert = aAlert().Warning(err.Error())
    66  	}
    67  
    68  	h.HTMLPlug(ctx, user, types.Panel{
    69  		Content: alert + formContent(aForm().
    70  			SetContent(formInfo.FieldList).
    71  			SetTabContents(formInfo.GroupFieldList).
    72  			SetTabHeaders(formInfo.GroupFieldHeaders).
    73  			SetPrefix(h.config.PrefixFixSlash()).
    74  			SetPrimaryKey(panel.GetPrimaryKey().Name).
    75  			SetUrl(h.routePath("menu_edit")).
    76  			SetHiddenFields(map[string]string{
    77  				form2.TokenKey:    h.authSrv().AddToken(),
    78  				form2.PreviousKey: h.routePath("menu") + getMenuPlugNameParams(plugName),
    79  			}).
    80  			SetOperationFooter(formFooter("new", false, false, false,
    81  				panel.GetForm().FormNewBtnWord)),
    82  			false, ctx.IsIframe(), false, ""),
    83  		Description: template2.HTML(panel.GetForm().Description),
    84  		Title:       template2.HTML(panel.GetForm().Title),
    85  	}, plugName)
    86  }
    87  
    88  // ShowEditMenu show edit menu page.
    89  func (h *Handler) ShowEditMenu(ctx *context.Context) {
    90  
    91  	plugName := getPlugNameFromReferer(ctx)
    92  
    93  	if ctx.Query("id") == "" {
    94  		h.getMenuInfoPanel(ctx, "", template.Get(h.config.Theme).Alert().Warning(errors.WrongID))
    95  
    96  		ctx.AddHeader("Content-Type", "text/html; charset=utf-8")
    97  		ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+getMenuPlugNameParams(plugName))
    98  		return
    99  	}
   100  
   101  	model := h.table("menu", ctx)
   102  	formInfo, err := model.GetDataWithId(parameter.BaseParam().WithPKs(ctx.Query("id")))
   103  
   104  	user := auth.Auth(ctx)
   105  
   106  	if err != nil {
   107  		h.HTMLPlug(ctx, user, template.WarningPanelWithDescAndTitle(err.Error(),
   108  			model.GetForm().Description, model.GetForm().Title), plugName)
   109  		return
   110  	}
   111  
   112  	h.showEditMenu(ctx, plugName, formInfo, nil)
   113  }
   114  
   115  func (h *Handler) showEditMenu(ctx *context.Context, plugName string, formInfo table.FormInfo, err error) {
   116  
   117  	var alert template2.HTML
   118  
   119  	if err != nil {
   120  		alert = aAlert().Warning(err.Error())
   121  	}
   122  
   123  	params := getMenuPlugNameParams(plugName)
   124  
   125  	panel := h.table("menu", ctx)
   126  
   127  	h.HTMLPlug(ctx, auth.Auth(ctx), types.Panel{
   128  		Content: alert + formContent(aForm().
   129  			SetContent(formInfo.FieldList).
   130  			SetTabContents(formInfo.GroupFieldList).
   131  			SetTabHeaders(formInfo.GroupFieldHeaders).
   132  			SetPrefix(h.config.PrefixFixSlash()).
   133  			SetPrimaryKey(panel.GetPrimaryKey().Name).
   134  			SetUrl(h.routePath("menu_edit")).
   135  			SetOperationFooter(formFooter("edit", false, false, false,
   136  				panel.GetForm().FormEditBtnWord)).
   137  			SetHiddenFields(map[string]string{
   138  				form2.TokenKey:    h.authSrv().AddToken(),
   139  				form2.PreviousKey: h.routePath("menu") + params,
   140  			}), false, ctx.IsIframe(), false, ""),
   141  		Description: template2.HTML(formInfo.Description),
   142  		Title:       template2.HTML(formInfo.Title),
   143  	}, plugName)
   144  }
   145  
   146  // DeleteMenu delete the menu of given id.
   147  func (h *Handler) DeleteMenu(ctx *context.Context) {
   148  	models.MenuWithId(guard.GetMenuDeleteParam(ctx).Id).SetConn(h.conn).Delete()
   149  	response.OkWithMsg(ctx, language.Get("delete succeed"))
   150  }
   151  
   152  // EditMenu edit the menu of given id.
   153  func (h *Handler) EditMenu(ctx *context.Context) {
   154  
   155  	param := guard.GetMenuEditParam(ctx)
   156  	params := getMenuPlugNameParams(param.PluginName)
   157  
   158  	if param.HasAlert() {
   159  		h.getMenuInfoPanel(ctx, param.PluginName, param.Alert)
   160  		ctx.AddHeader("Content-Type", "text/html; charset=utf-8")
   161  		ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   162  		return
   163  	}
   164  
   165  	menuModel := models.MenuWithId(param.Id).SetConn(h.conn)
   166  
   167  	// TODO: use transaction
   168  	deleteRolesErr := menuModel.DeleteRoles()
   169  	if db.CheckError(deleteRolesErr, db.DELETE) {
   170  		formInfo, _ := h.table("menu", ctx).GetDataWithId(parameter.BaseParam().WithPKs(param.Id))
   171  		h.showEditMenu(ctx, param.PluginName, formInfo, deleteRolesErr)
   172  		ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   173  		return
   174  	}
   175  	for _, roleId := range param.Roles {
   176  		_, addRoleErr := menuModel.AddRole(roleId)
   177  		if db.CheckError(addRoleErr, db.INSERT) {
   178  			formInfo, _ := h.table("menu", ctx).GetDataWithId(parameter.BaseParam().WithPKs(param.Id))
   179  			h.showEditMenu(ctx, param.PluginName, formInfo, addRoleErr)
   180  			ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   181  			return
   182  		}
   183  	}
   184  
   185  	_, updateErr := menuModel.Update(param.Title, param.Icon, param.Uri, param.Header, param.PluginName, param.ParentId)
   186  
   187  	if db.CheckError(updateErr, db.UPDATE) {
   188  		formInfo, _ := h.table("menu", ctx).GetDataWithId(parameter.BaseParam().WithPKs(param.Id))
   189  		h.showEditMenu(ctx, param.PluginName, formInfo, updateErr)
   190  		ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   191  		return
   192  	}
   193  
   194  	h.getMenuInfoPanel(ctx, param.PluginName, "")
   195  	ctx.AddHeader("Content-Type", "text/html; charset=utf-8")
   196  	ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   197  }
   198  
   199  // NewMenu create a new menu item.
   200  func (h *Handler) NewMenu(ctx *context.Context) {
   201  
   202  	param := guard.GetMenuNewParam(ctx)
   203  	params := getMenuPlugNameParams(param.PluginName)
   204  
   205  	if param.HasAlert() {
   206  		h.getMenuInfoPanel(ctx, param.PluginName, param.Alert)
   207  		ctx.AddHeader("Content-Type", "text/html; charset=utf-8")
   208  		ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   209  		return
   210  	}
   211  
   212  	user := auth.Auth(ctx)
   213  
   214  	// TODO: use transaction
   215  	menuModel, createErr := models.Menu().SetConn(h.conn).
   216  		New(param.Title, param.Icon, param.Uri, param.Header, param.PluginName, param.ParentId,
   217  			(menu.GetGlobalMenu(user, h.conn, ctx.Lang(), param.PluginName)).MaxOrder+1)
   218  
   219  	if db.CheckError(createErr, db.INSERT) {
   220  		h.showNewMenu(ctx, createErr)
   221  		return
   222  	}
   223  
   224  	for _, roleId := range param.Roles {
   225  		_, addRoleErr := menuModel.AddRole(roleId)
   226  		if db.CheckError(addRoleErr, db.INSERT) {
   227  			h.showNewMenu(ctx, addRoleErr)
   228  			return
   229  		}
   230  	}
   231  
   232  	menu.GetGlobalMenu(user, h.conn, ctx.Lang(), param.PluginName).AddMaxOrder()
   233  
   234  	h.getMenuInfoPanel(ctx, param.PluginName, "")
   235  	ctx.AddHeader("Content-Type", "text/html; charset=utf-8")
   236  	ctx.AddHeader(constant.PjaxUrlHeader, h.routePath("menu")+params)
   237  }
   238  
   239  // MenuOrder change the order of menu items.
   240  func (h *Handler) MenuOrder(ctx *context.Context) {
   241  
   242  	var data []map[string]interface{}
   243  	_ = json.Unmarshal([]byte(ctx.FormValue("_order")), &data)
   244  
   245  	models.Menu().SetConn(h.conn).ResetOrder([]byte(ctx.FormValue("_order")))
   246  
   247  	response.Ok(ctx)
   248  }
   249  
   250  func (h *Handler) getMenuInfoPanel(ctx *context.Context, plugName string, alert template2.HTML) {
   251  	user := auth.Auth(ctx)
   252  
   253  	if plugName == "" {
   254  		plugName = ctx.Query("__plugin_name")
   255  	}
   256  
   257  	tree := aTree().
   258  		SetTree((menu.GetGlobalMenu(user, h.conn, ctx.Lang(), plugName)).List).
   259  		SetEditUrl(h.routePath("menu_edit_show")).
   260  		SetUrlPrefix(h.config.Prefix()).
   261  		SetDeleteUrl(h.routePath("menu_delete")).
   262  		SetOrderUrl(h.routePath("menu_order")).
   263  		GetContent()
   264  
   265  	var (
   266  		header   = aTree().GetTreeHeader()
   267  		box      = aBox().SetHeader(header).SetBody(tree).GetContent()
   268  		col1     = aCol().SetSize(types.SizeMD(6)).SetContent(box).GetContent()
   269  		panel    = h.table("menu", ctx)
   270  		formInfo = panel.GetNewFormInfo()
   271  	)
   272  
   273  	newForm := menuFormContent(aForm().
   274  		SetPrefix(h.config.PrefixFixSlash()).
   275  		SetUrl(h.routePath("menu_new")).
   276  		SetPrimaryKey(panel.GetPrimaryKey().Name).
   277  		SetHiddenFields(map[string]string{
   278  			form2.TokenKey:    h.authSrv().AddToken(),
   279  			form2.PreviousKey: h.routePath("menu") + getMenuPlugNameParams(plugName),
   280  		}).
   281  		SetOperationFooter(formFooter("menu", false, false, false,
   282  			panel.GetForm().FormNewBtnWord)).
   283  		SetTitle("New").
   284  		SetContent(formInfo.FieldList).
   285  		SetTabContents(formInfo.GroupFieldList).
   286  		SetTabHeaders(formInfo.GroupFieldHeaders))
   287  
   288  	col2 := aCol().SetSize(types.SizeMD(6)).SetContent(newForm).GetContent()
   289  
   290  	row := aRow().SetContent(col1 + col2).GetContent()
   291  
   292  	h.HTMLPlug(ctx, user, types.Panel{
   293  		Content:     alert + row,
   294  		Description: "Menus Manage",
   295  		Title:       "Menus Manage",
   296  	}, plugName)
   297  }