93 lines
2.4 KiB
Go
93 lines
2.4 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 monthInterval(y int, m time.Month) (firstDay, lastDay time.Time) {
|
|
firstDay = time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
|
|
lastDay = time.Date(y, m+1, 1, 0, 0, 0, -1, time.UTC)
|
|
return firstDay, lastDay
|
|
}
|
|
|
|
func (h *Server) orders(_ *http.Request) (templ.Component, int, error) {
|
|
var (
|
|
y int
|
|
m time.Month
|
|
)
|
|
y, m, _ = time.Now().Date()
|
|
first, last := monthInterval(y, m)
|
|
orders, err := h.s.GetOrders(first, last)
|
|
return templates.OrdersPage(first.Format(config.DateFormat), last.Format(config.DateFormat), orders), http.StatusOK, err
|
|
}
|
|
|
|
func (h *Server) ordersSearch(r *http.Request) (templ.Component, int, error) {
|
|
from, err := time.Parse(config.DateFormat, r.URL.Query().Get("from"))
|
|
if err != nil {
|
|
from = time.Time{}
|
|
}
|
|
to, err := time.Parse(config.DateFormat, r.URL.Query().Get("to"))
|
|
if err != nil {
|
|
to = time.Time{}
|
|
}
|
|
data, err := h.s.GetOrders(from, to)
|
|
return templates.OrdersTable(data), 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
|
|
}
|