1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/routes/summary.go

79 lines
1.9 KiB
Go
Raw Normal View History

package routes
import (
2020-10-09 22:37:16 +03:00
conf "github.com/muety/wakapi/config"
2020-03-31 13:22:17 +03:00
"github.com/muety/wakapi/models"
"github.com/muety/wakapi/services"
"github.com/muety/wakapi/utils"
"net/http"
2019-05-19 21:06:07 +03:00
)
type SummaryHandler struct {
summarySrvc *services.SummaryService
2020-10-09 22:37:16 +03:00
config *conf.Config
2019-05-21 22:46:23 +03:00
}
func NewSummaryHandler(summaryService *services.SummaryService) *SummaryHandler {
return &SummaryHandler{
summarySrvc: summaryService,
2020-10-09 22:37:16 +03:00
config: conf.Get(),
}
}
2020-03-31 12:24:44 +03:00
func (h *SummaryHandler) ApiGet(w http.ResponseWriter, r *http.Request) {
summary, err, status := h.loadUserSummary(r)
2020-02-20 16:28:55 +03:00
if err != nil {
w.WriteHeader(status)
w.Write([]byte(err.Error()))
return
}
utils.RespondJSON(w, http.StatusOK, summary)
}
func (h *SummaryHandler) GetIndex(w http.ResponseWriter, r *http.Request) {
if h.config.IsDev() {
loadTemplates()
2020-02-20 17:39:56 +03:00
}
2020-02-20 17:54:20 +03:00
q := r.URL.Query()
if q.Get("interval") == "" && q.Get("from") == "" {
q.Set("interval", "today")
r.URL.RawQuery = q.Encode()
}
summary, err, status := h.loadUserSummary(r)
2020-02-20 16:28:55 +03:00
if err != nil {
2020-10-09 22:37:16 +03:00
respondAlert(w, err.Error(), "", conf.SummaryTemplate, status)
return
}
user := r.Context().Value(models.UserKey).(*models.User)
if user == nil {
2020-10-09 22:37:16 +03:00
respondAlert(w, "unauthorized", "", conf.SummaryTemplate, http.StatusUnauthorized)
2020-02-20 16:28:55 +03:00
return
}
2020-03-31 12:24:44 +03:00
vm := models.SummaryViewModel{
Summary: summary,
LanguageColors: utils.FilterLanguageColors(h.config.App.LanguageColors, summary),
ApiKey: user.ApiKey,
2020-03-31 12:24:44 +03:00
}
2020-10-09 22:37:16 +03:00
templates[conf.SummaryTemplate].Execute(w, vm)
2020-02-20 16:28:55 +03:00
}
func (h *SummaryHandler) loadUserSummary(r *http.Request) (*models.Summary, error, int) {
summaryParams, err := utils.ParseSummaryParams(r)
if err != nil {
return nil, err, http.StatusBadRequest
2019-05-19 21:34:26 +03:00
}
summary, err := h.summarySrvc.Construct(summaryParams.From, summaryParams.To, summaryParams.User, summaryParams.Recompute) // 'to' is always constant
2020-02-20 16:28:55 +03:00
if err != nil {
return nil, err, http.StatusInternalServerError
}
2020-02-20 16:28:55 +03:00
return summary, nil, http.StatusOK
2019-05-19 21:14:57 +03:00
}