74 lines
1.6 KiB
Go
74 lines
1.6 KiB
Go
package orders
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"math"
|
|
"net/http"
|
|
"piekarnikgosipl/data"
|
|
"strconv"
|
|
)
|
|
|
|
type listItem struct {
|
|
id string
|
|
count int // count multiplied by 100 to allow for half item purchases
|
|
}
|
|
|
|
type order struct {
|
|
name string
|
|
phone string
|
|
items []listItem
|
|
}
|
|
|
|
func parseFloat(input string) (int, error) {
|
|
val, err := strconv.ParseFloat(input, 64)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("Invalid float format")
|
|
}
|
|
|
|
if val < 0 || val > 100 {
|
|
return 0, fmt.Errorf("Value must be between 0 and 100")
|
|
}
|
|
|
|
doubled := val * 2
|
|
if math.Abs(doubled-math.Round(doubled)) > 1e-9 {
|
|
return 0, fmt.Errorf("Value must be a multiple of 0.5")
|
|
}
|
|
|
|
return int(math.Round(val * 100)), nil
|
|
|
|
}
|
|
|
|
func parseOrder(r *http.Request) (order, error) {
|
|
var o order
|
|
var err error
|
|
var errorList []error
|
|
o.name = r.PostFormValue("name")
|
|
if o.name == "" {
|
|
errorList = append(errorList, fmt.Errorf("Invalid name"))
|
|
}
|
|
o.phone, err = parseAndValidatePolishMobile(r.PostFormValue("phone"))
|
|
if err != nil {
|
|
errorList = append(errorList, err)
|
|
}
|
|
for _, item := range data.Swieta {
|
|
count, err := parseFloat(r.PostFormValue(item.Id))
|
|
if err != nil {
|
|
errorList = append(errorList, fmt.Errorf("Can't parse the count for %v: %e", item.Name, err))
|
|
continue
|
|
}
|
|
if count%10 == 5 && !item.Halveable {
|
|
errorList = append(errorList, fmt.Errorf("This item can't be bought in fractions %v", item.Name))
|
|
continue
|
|
}
|
|
o.items = append(o.items, listItem{item.Id, count})
|
|
}
|
|
return o, errors.Join(errorList...)
|
|
}
|
|
|
|
func OrderHandler(w http.ResponseWriter, r *http.Request) {
|
|
o, err := parseOrder(r)
|
|
log.Println(o, err)
|
|
fmt.Fprintf(w, "%v, %v", o, err)
|
|
}
|