92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/a-h/templ"
|
|
|
|
"git.bronku.xyz/bronku/cake-order-tracker/config"
|
|
"git.bronku.xyz/bronku/cake-order-tracker/models"
|
|
"git.bronku.xyz/bronku/cake-order-tracker/server/templates"
|
|
)
|
|
|
|
func weekInterval(t time.Time) (firstDay, lastDay time.Time) {
|
|
monday := t.AddDate(0, 0, -((int(t.Weekday()) + 6) % 7))
|
|
sunday := monday.AddDate(0, 0, 6)
|
|
return monday, sunday
|
|
}
|
|
|
|
func (h *Server) orders(r *http.Request) (templ.Component, int, error) {
|
|
now := time.Now()
|
|
weekFirst, weekLast := weekInterval(now)
|
|
|
|
first, last := weekFirst, weekLast
|
|
if from := r.URL.Query().Get("from"); from != "" {
|
|
if t, err := time.Parse(config.DateFormat, from); err == nil {
|
|
first = t
|
|
}
|
|
}
|
|
if to := r.URL.Query().Get("to"); to != "" {
|
|
if t, err := time.Parse(config.DateFormat, to); err == nil {
|
|
last = t
|
|
}
|
|
}
|
|
|
|
today := now.Format(config.DateFormat)
|
|
tomorrow := now.AddDate(0, 0, 1).Format(config.DateFormat)
|
|
|
|
orders, err := h.s.GetOrders(first, last)
|
|
return templates.OrdersPage(first.Format(config.DateFormat), last.Format(config.DateFormat), today, tomorrow, orders), http.StatusOK, err
|
|
}
|
|
|
|
func (h *Server) cakes(_ *http.Request) (templ.Component, int, error) {
|
|
data, err := h.s.GetCakes()
|
|
return templates.CakesPage(data), http.StatusOK, err
|
|
}
|
|
|
|
func (h *Server) cake(r *http.Request) (templ.Component, int, error) {
|
|
url := strings.Split(r.URL.Path, "/")
|
|
if len(url) < 3 || url[2] == "" {
|
|
return templates.CakePage(models.Cake{}), http.StatusOK, nil
|
|
}
|
|
|
|
id, err := strconv.Atoi(url[2])
|
|
if err != nil {
|
|
return nil, http.StatusBadRequest, err
|
|
}
|
|
|
|
data, err := h.s.GetCake(id)
|
|
if err != nil {
|
|
return nil, http.StatusNotFound, err
|
|
}
|
|
|
|
return templates.CakePage(data), http.StatusOK, nil
|
|
}
|
|
|
|
func (h *Server) order(r *http.Request) (templ.Component, int, error) {
|
|
var err error
|
|
catalogue, err := h.s.GetCakes()
|
|
if err != nil {
|
|
return nil, http.StatusInternalServerError, err
|
|
}
|
|
|
|
url := strings.Split(r.URL.Path, "/")
|
|
if len(url) < 3 || url[2] == "" {
|
|
return templates.OrderPage(models.Order{Date: time.Now()}, catalogue), http.StatusOK, nil
|
|
}
|
|
|
|
id, err := strconv.Atoi(url[2])
|
|
if err != nil {
|
|
return nil, http.StatusBadRequest, err
|
|
}
|
|
|
|
order, err := h.s.GetOrder(id)
|
|
if err != nil {
|
|
return nil, http.StatusNotFound, err
|
|
}
|
|
|
|
return templates.OrderPage(order, catalogue), http.StatusOK, nil
|
|
}
|