Elektromarket/views/views.go

86 lines
2.4 KiB
Go

package views
import (
"net/http"
"strconv"
"html/template"
. "Elektromarket/models"
)
func ExecuteView(w http.ResponseWriter, r *http.Request, templateName string, data map[string]interface{}) {
data["cart"] = ShoppingCart
t, _ := template.ParseFiles(templateName, "templates/base.html")
t.ExecuteTemplate(w, "base", data)
}
func IndexView(p Page, w http.ResponseWriter, r *http.Request) {
ExecuteView(w, r, p.Template, p.Data)
}
func CategoryView(p Page, w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query()["id"][0])
if err == nil {
p.Data = map[string]interface{}{
"category": GetCategoryById(id),
"products": GetCategoryProducts(id),
}
}
ExecuteView(w, r, p.Template, p.Data)
}
func ProductView(p Page, w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query()["id"][0])
if err == nil {
p.Data = map[string]interface{}{
"product": GetProductById(id),
}
}
ExecuteView(w, r, p.Template, p.Data)
}
func CartView(p Page, w http.ResponseWriter, r *http.Request) {
ExecuteView(w, r, p.Template, p.Data)
}
func AddToCartView(p Page, w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query()["id"][0])
quantity, erro := strconv.Atoi(r.URL.Query()["quantity"][0])
if err == nil && erro == nil {
prod := GetProductById(id)
if prod.Quantity >= quantity {
prod.Quantity -= quantity
prod.Save()
var exists bool = false
for i:= range ShoppingCart.Products {
if prod.Id == ShoppingCart.Products[i].Product.Id {
exists = true
ShoppingCart.Products[i].Quantity += quantity
break
}
}
if !exists {
ShoppingCart.Products = append(ShoppingCart.Products, CartProduct{prod, quantity, 0})
}
ShoppingCart.Calculate()
}
}
ExecuteView(w, r, "templates/cart.html", p.Data)
}
func RemoveFromCartView(p Page, w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query()["id"][0])
if err == nil {
for i:= range ShoppingCart.Products {
if id == ShoppingCart.Products[i].Product.Id {
prod := GetProductById(id)
prod.Quantity += ShoppingCart.Products[i].Quantity
prod.Save()
ShoppingCart.Products = append(ShoppingCart.Products[:i], ShoppingCart.Products[i+1:]...)
break
}
}
ShoppingCart.Calculate()
}
ExecuteView(w, r, "templates/cart.html", p.Data)
}