aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/admin.go
blob: 8531011ef0ecc785f79475d99d5bb3a7c13e91af (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package handler

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"sh.org.ru/pkg/model"
	"sh.org.ru/pkg/tpl"
)

func (h *Handler) Admin(c echo.Context) error {
	quotes := make([]model.Quote, 0, 20)
	count, err := h.DB.NewSelect().
		Model((*model.Quote)(nil)).
		Order("id ASC").
		Where("approved = ?", false).
		ScanAndCount(c.Request().Context(), &quotes)
	if err != nil {
		return err
	}

	return tpl.Admin(quotes, count).Render(c.Request().Context(), c.Response())
}

func (h *Handler) AdminAction(c echo.Context) error {
	form := new(tpl.AdminForm)
	if err := c.Bind(form); err != nil {
		return err
	}

	switch form.Action {
	case "approve":
		_, err := h.DB.NewUpdate().
			Model(&model.Quote{
				ID:       int64(form.ID),
				Approved: true,
			}).
			Column("approved").
			WherePK("id").
			Exec(c.Request().Context())
		if err != nil {
			return err
		}
	case "decline":
		_, err := h.DB.NewDelete().
			Model(&model.Quote{
				ID: int64(form.ID),
			}).
			WherePK("id").
			Exec(c.Request().Context())
		if err != nil {
			return err
		}
	}

	return c.Redirect(http.StatusFound, "/admin/")
}