cml04-falcon-ui/handlers/barcodes.go

83 lines
2.3 KiB
Go
Raw Normal View History

2024-10-06 06:12:43 +02:00
package handlers
import (
2024-10-07 10:25:25 +02:00
"fmt"
2024-10-06 06:12:43 +02:00
"net/http"
2024-10-07 10:25:25 +02:00
"strings"
2024-10-06 06:12:43 +02:00
"text/template"
"git.espin.casa/albert/cml04-falcon-ui/storage"
2024-10-07 10:25:25 +02:00
"git.espin.casa/albert/cml04-falcon-ui/types"
2024-10-06 06:12:43 +02:00
"github.com/julienschmidt/httprouter"
)
func BarcodesHandler(storage storage.Storager) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
2024-10-07 10:25:25 +02:00
// get method
if r.Method == http.MethodGet {
// parse template files
t, _ := template.ParseFiles("templates/base.html", "templates/barcodes.html")
// execute templates
err := t.Execute(w, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// post method
if r.Method == http.MethodPost {
// barcodes holder
barcodes := []types.Barcode{}
// parse form data from formulary
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// barcode
codigo := r.FormValue("codigo")
// date range
fechas := r.FormValue("fechas")
// loading bed
evacuadores := r.FormValue("evacuadores")
// check form values
if codigo != "" {
// call storager
data, err := storage.Barcode(r.Context(), codigo)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// append barcode to holder
barcodes = append(barcodes, *data)
} else {
inicio := strings.Split(fechas, "-")[0]
inicio = strings.TrimSpace(inicio)
final := strings.Split(fechas, "-")[1]
final = strings.TrimSpace(final)
// get loading bed from string
lb, ok := types.MapLoadingBed[evacuadores]
// if loading bed not found
if !ok {
http.Error(w, fmt.Errorf("loading bed value not found").Error(), http.StatusInternalServerError)
return
}
// call storager
data, err := storage.ListBarcode(r.Context(), lb, inicio, final)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//set barcodes
barcodes = data
}
// parse template files
t, _ := template.ParseFiles("templates/base.html", "templates/barcodes.html")
// execute templates
err := t.Execute(w, barcodes)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-10-06 06:12:43 +02:00
}
}
}