This repository has been archived by the owner on Dec 13, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcart.go
90 lines (71 loc) · 1.57 KB
/
cart.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package shopy
import (
"net/http"
"strconv"
"strings"
)
// Cart does exactly what is says
type Cart struct {
RawList map[int]int
Products []*CartItem
Locked bool
}
// CartItem handles products and its quantity
type CartItem struct {
*Product
Quantity int
}
// FillProducts ...
func (c *Cart) FillProducts(service ProductService) error {
ids := "("
if len(c.RawList) == 0 {
return nil
}
for k := range c.RawList {
ids += strconv.Itoa(k) + ", "
}
ids = strings.TrimSuffix(ids, ", ") + ")"
products, err := service.GetsWhereIn(0, 0, "ID", "ID", ids)
if err != nil {
return err
}
for k := range products {
c.Products = append(c.Products, &CartItem{
Quantity: c.RawList[products[k].ID],
Product: products[k],
})
}
return nil
}
// GetTotal display the order total price
func (c Cart) GetTotal() int {
if c.Products == nil {
return 0
}
total := 0
for k := range c.Products {
total += c.Products[k].Price * c.Products[k].Quantity
}
return total
}
// GetDescription is used for the payment procedure
func (c Cart) GetDescription() string {
if c.Products == nil {
return ""
}
description := ""
for _, product := range c.Products {
description += strconv.Itoa(product.Quantity) + " x " + product.Name + "\n"
}
return description
}
// GetPrice displays the product price * quantity
func (i CartItem) GetPrice() int {
return i.Price * i.Quantity
}
// CartService ...
type CartService interface {
Save(w http.ResponseWriter, c *Cart) error
Get(w http.ResponseWriter, r *http.Request) (*Cart, error)
Reset(w http.ResponseWriter) error
}