High performance, self-hosted, newsletter and mailing list manager with a modern dashboard. Single binary app.
JavaScript campaigncampaign-managementemail-marketingemail-subscriptionlistmonkmailing-listnewsletternewsletter-managementnewsletter-softwareself-hostedsms-gatewaysmtptransactional-emails
Add searching and sorting to user/list roles.
Kailash Nadh2574c4e32d18
diff --git a/cmd/roles.go b/cmd/roles.goindex efd6e7ba..9d3f5e0e 100644--- a/cmd/roles.go+++ b/cmd/roles.go@@ -12,6 +12,13 @@ import ("gopkg.in/volatiletech/null.v6")+// rolesQueryDefaults is the allow list of filter query params.+var rolesQueryDefaults = map[string]string{+ "query": "",+ "order_by": "created_at",+ "order": "asc",+}+// roleRow is the normalized shape of a user/list role for the roles table view.type roleRow struct {ID int@@ -26,6 +33,7 @@ type rolesView struct {Type stringRoles []roleRow+ Page models.PageProps}// permGroup is a group of granular permissions as defined in permissions.json.@@ -50,7 +58,8 @@ func (a *App) ViewUserRoles(c echo.Context) error {return auth.ErrPermDenied}- roles, err := a.core.GetRoles()+ q := makeQuery(c.Request().URL.Query(), rolesQueryDefaults)+ roles, err := a.core.GetRoles(q.Get("query"), q.Get("order_by"), q.Get("order"))if err != nil {return err}@@ -64,6 +73,7 @@ func (a *App) ViewUserRoles(c echo.Context) error {adminView: newAdminView(c, a.i18n.T("users.userRoles"), "", "users.user-roles"),Type: "user",Roles: rows,+ Page: models.NewPageProps(q, len(rows), 1, 0),}return c.Render(http.StatusOK, "admin-roles", data)@@ -75,7 +85,8 @@ func (a *App) ViewListRoles(c echo.Context) error {return auth.ErrPermDenied}- roles, err := a.core.GetListRoles()+ q := makeQuery(c.Request().URL.Query(), rolesQueryDefaults)+ roles, err := a.core.GetListRoles(q.Get("query"), q.Get("order_by"), q.Get("order"))if err != nil {return err}@@ -89,6 +100,7 @@ func (a *App) ViewListRoles(c echo.Context) error {adminView: newAdminView(c, a.i18n.T("users.listRoles"), "", "users.list-roles"),Type: "list",Roles: rows,+ Page: models.NewPageProps(q, len(rows), 1, 0),}return c.Render(http.StatusOK, "admin-roles", data)@@ -147,7 +159,7 @@ func (a *App) ViewListRole(c echo.Context) error {if c.Get("id") != nil {// There's no core getter for a single list role, so fetch all and pick the one.id := getID(c)- roles, err := a.core.GetListRoles()+ roles, err := a.core.GetListRoles("", "", "")if err != nil {return err}@@ -199,7 +211,7 @@ func (a *App) parsePermGroups() ([]permGroup, error) {// GetUserRoles retrieves roles.func (a *App) GetUserRoles(c echo.Context) error {// Get all roles.- out, err := a.core.GetRoles()+ out, err := a.core.GetRoles(c.QueryParam("query"), c.QueryParam("order_by"), c.QueryParam("order"))if err != nil {return err}@@ -210,7 +222,7 @@ func (a *App) GetUserRoles(c echo.Context) error {// GeListRoles retrieves roles.func (a *App) GeListRoles(c echo.Context) error {// Get all roles.- out, err := a.core.GetListRoles()+ out, err := a.core.GetListRoles(c.QueryParam("query"), c.QueryParam("order_by"), c.QueryParam("order"))if err != nil {return err}diff --git a/cmd/settings.go b/cmd/settings.goindex 99ad8f7c..00fa9b58 100644--- a/cmd/settings.go+++ b/cmd/settings.go@@ -119,7 +119,7 @@ func (a *App) ViewSettings(c echo.Context) error {// Roles for the OIDC default-role dropdowns (security tab).var userRoles, listRoles []roleOptionif can(auth.GetUser(c), auth.PermRolesGet) {- ur, err := a.core.GetRoles()+ ur, err := a.core.GetRoles("", "", "")if err != nil {return err}@@ -127,7 +127,7 @@ func (a *App) ViewSettings(c echo.Context) error {userRoles = append(userRoles, roleOption{ID: r.ID, Name: r.Name.String})}- lr, err := a.core.GetListRoles()+ lr, err := a.core.GetListRoles("", "", "")if err != nil {return err}diff --git a/cmd/users.go b/cmd/users.goindex 553e40a3..cf8c5a3a 100644--- a/cmd/users.go+++ b/cmd/users.go@@ -173,11 +173,11 @@ func (a *App) ViewProfile(c echo.Context) error {// getRoles fetches user and list roles for the user-form role selectors.func (a *App) getRoles() ([]auth.Role, []auth.ListRole, error) {- userRoles, err := a.core.GetRoles()+ userRoles, err := a.core.GetRoles("", "", "")if err != nil {return nil, nil, err}- listRoles, err := a.core.GetListRoles()+ listRoles, err := a.core.GetListRoles("", "", "")if err != nil {return nil, nil, err}diff --git a/internal/core/core.go b/internal/core/core.goindex e6cce38a..4f7f64d2 100644--- a/internal/core/core.go+++ b/internal/core/core.go@@ -72,6 +72,7 @@ var (campQuerySortFields = []string{"name", "status", "created_at", "updated_at"}subQuerySortFields = []string{"email", "status", "name", "created_at", "updated_at"}userQuerySortFields = []string{"username", "email", "created_at", "loggedin_at"}+ roleQuerySortFields = []string{"name", "created_at", "updated_at"}templateQuerySortFields = []string{"name", "type", "created_at", "updated_at"}listQuerySortFields = []string{"name", "status", "created_at", "updated_at", "subscriber_count"})diff --git a/internal/core/roles.go b/internal/core/roles.goindex 63cfa624..a4f00008 100644--- a/internal/core/roles.go+++ b/internal/core/roles.go@@ -10,9 +10,16 @@ import ()// GetRoles retrieves all roles.-func (c *Core) GetRoles() ([]auth.Role, error) {- out := []auth.Role{}- if err := c.q.GetUserRoles.Select(&out, nil); err != nil {+func (c *Core) GetRoles(searchStr, orderBy, order string) ([]auth.Role, error) {+ if order == "" {+ order = SortAsc+ }++ var (+ out = []auth.Role{}+ queryStr, stmt = makeSearchQuery(searchStr, orderBy, order, c.q.GetUserRoles, roleQuerySortFields)+ )+ if err := c.db.Select(&out, stmt, 0, queryStr); err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError,c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))}@@ -23,7 +30,8 @@ func (c *Core) GetRoles() ([]auth.Role, error) {// GetRole retrieves a role.func (c *Core) GetRole(id int) (auth.Role, error) {out := []auth.Role{}- if err := c.q.GetUserRoles.Select(&out, id); err != nil {+ _, stmt := makeSearchQuery("", "", SortAsc, c.q.GetUserRoles, roleQuerySortFields)+ if err := c.db.Select(&out, stmt, id, ""); err != nil {return auth.Role{}, echo.NewHTTPError(http.StatusInternalServerError,c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))}@@ -38,9 +46,16 @@ func (c *Core) GetRole(id int) (auth.Role, error) {}// GetListRoles retrieves all list roles.-func (c *Core) GetListRoles() ([]auth.ListRole, error) {- out := []auth.ListRole{}- if err := c.q.GetListRoles.Select(&out); err != nil {+func (c *Core) GetListRoles(searchStr, orderBy, order string) ([]auth.ListRole, error) {+ if order == "" {+ order = SortAsc+ }++ var (+ out = []auth.ListRole{}+ queryStr, stmt = makeSearchQuery(searchStr, orderBy, order, c.q.GetListRoles, roleQuerySortFields)+ )+ if err := c.db.Select(&out, stmt, queryStr); err != nil {return nil, echo.NewHTTPError(http.StatusInternalServerError,c.i18n.Ts("globals.messages.errorFetching", "name", "role", "error", pqErrMsg(err)))}diff --git a/models/queries.go b/models/queries.goindex 9bec782b..eaf700fc 100644--- a/models/queries.go+++ b/models/queries.go@@ -132,8 +132,8 @@ type Queries struct {DeleteUserSessions *sqlx.Stmt `query:"delete-user-sessions"`CreateRole *sqlx.Stmt `query:"create-role"`- GetUserRoles *sqlx.Stmt `query:"get-user-roles"`- GetListRoles *sqlx.Stmt `query:"get-list-roles"`+ GetUserRoles string `query:"get-user-roles"`+ GetListRoles string `query:"get-list-roles"`UpdateRole *sqlx.Stmt `query:"update-role"`DeleteRole *sqlx.Stmt `query:"delete-role"`UpsertListPermissions *sqlx.Stmt `query:"upsert-list-permissions"`diff --git a/queries/roles.sql b/queries/roles.sqlindex a5dc3059..deb057ff 100644--- a/queries/roles.sql+++ b/queries/roles.sql@@ -2,6 +2,7 @@WITH mainroles AS (SELECT ur.* FROM roles ur WHERE type = 'user' AND ur.parent_id IS NULL ANDCASE WHEN $1::INT != 0 THEN ur.id = $1 ELSE TRUE END+ AND ($2 = '' OR TO_TSVECTOR(ur.name) @@ PLAINTO_TSQUERY($2) OR ur.name ILIKE ('%' || $2 || '%'))),listPerms AS (SELECT ur.parent_id, JSONB_AGG(JSONB_BUILD_OBJECT('id', ur.list_id, 'name', lists.name, 'permissions', ur.permissions)) AS listPerms@@ -10,11 +11,12 @@ listPerms AS (WHERE ur.parent_id IS NOT NULL GROUP BY ur.parent_id)SELECT p.*, COALESCE(l.listPerms, '[]'::JSONB) AS "list_permissions" FROM mainroles p- LEFT JOIN listPerms l ON p.id = l.parent_id ORDER BY p.created_at;+ LEFT JOIN listPerms l ON p.id = l.parent_id ORDER BY %order%;-- name: get-list-rolesWITH mainroles AS (SELECT ur.* FROM roles ur WHERE type = 'list' AND ur.parent_id IS NULL+ AND ($1 = '' OR TO_TSVECTOR(ur.name) @@ PLAINTO_TSQUERY($1) OR ur.name ILIKE ('%' || $1 || '%'))),listPerms AS (SELECT ur.parent_id, JSONB_AGG(JSONB_BUILD_OBJECT('id', ur.list_id, 'name', lists.name, 'permissions', ur.permissions)) AS listPerms@@ -23,7 +25,7 @@ listPerms AS (WHERE ur.parent_id IS NOT NULL GROUP BY ur.parent_id)SELECT p.*, COALESCE(l.listPerms, '[]'::JSONB) AS "list_permissions" FROM mainroles p- LEFT JOIN listPerms l ON p.id = l.parent_id ORDER BY p.created_at;+ LEFT JOIN listPerms l ON p.id = l.parent_id ORDER BY %order%;-- name: create-role@@ -46,7 +48,7 @@ INSERT INTO roles (parent_id, list_id, permissions, type)DELETE FROM roles WHERE parent_id=$1 AND list_id=$2;-- name: update-role-UPDATE roles SET name=$2, permissions=$3 WHERE id=$1 and parent_id IS NULL RETURNING *;+UPDATE roles SET name=$2, permissions=$3, updated_at=NOW() WHERE id=$1 and parent_id IS NULL RETURNING *;-- name: delete-roleDELETE FROM roles WHERE id=$1;diff --git a/static/admin/views/roles.html b/static/admin/views/roles.htmlindex 701a2c71..0ebdf006 100644--- a/static/admin/views/roles.html+++ b/static/admin/views/roles.html@@ -15,6 +15,13 @@</div></div><div class="col-8 hstack justify-end buttons">+ <form method="get" action="{{ $base }}" class="search-form">+ {{- $d.Page.FormFields "query" -}}+ <fieldset class="group">+ <input name="query" aria-label="Search" data-testid="query" placeholder="Search" value="{{ $d.Page.Query }}" autofocus />+ <button type="submit" class="outline external" data-testid="btn-query" aria-label="Search">{{ Icon "search" }}</button>+ </fieldset>+ </form>{{- if $d.Can "roles:manage" }}<a href="{{ $base }}/new" class="button" data-variant="primary" data-testid="btn-new">{{ Icon "plus" }} {{ .L.T "globals.buttons.new" }}@@ -28,9 +35,9 @@<table><thead><tr>- <th>{{ .L.Tc "users.role" 1 }}</th>- <th>{{ .L.T "globals.fields.createdAt" }}</th>- <th>{{ .L.T "globals.fields.updatedAt" }}</th>+ <th>{{ $d.Page.SortLink $base "name" (.L.Tc "users.role" 1) }}</th>+ <th>{{ $d.Page.SortLink $base "created_at" (.L.T "globals.fields.createdAt") }}</th>+ <th>{{ $d.Page.SortLink $base "updated_at" (.L.T "globals.fields.updatedAt") }}</th><th class="actions align-right"></th></tr></thead>