shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
2,479 bytes raw
1
package models
2
3
import (
4
	"database/sql"
5
	"encoding/json"
6
	"fmt"
7
)
8
9
type Cart_Item struct {
10
	Product_ID int
11
	Variant_ID int
12
	Quantity   int
13
}
14
15
type Cart_Item_Detail struct {
16
	Product_ID int
17
	Variant_ID int
18
	Quantity   int
19
	Name       string
20
	Size       string
21
	Price      int
22
	Image_URL  string
23
	Subtotal   int
24
}
25
26
type Cart map[string]Cart_Item
27
28
func cart_key(product_id, variant_id int) string {
29
	return fmt.Sprintf("%d_%d", product_id, variant_id)
30
}
31
32
func Parse_Cart(cart_json string) (Cart, error) {
33
	if cart_json == "" {
34
		return make(Cart), nil
35
	}
36
37
	var cart Cart
38
	if err := json.Unmarshal([]byte(cart_json), &cart); err != nil {
39
		return nil, err
40
	}
41
	return cart, nil
42
}
43
44
func Serialize_Cart(cart Cart) (string, error) {
45
	data, err := json.Marshal(cart)
46
	if err != nil {
47
		return "", err
48
	}
49
	return string(data), nil
50
}
51
52
func Add_To_Cart(cart Cart, product_id, variant_id, quantity int) Cart {
53
	key := cart_key(product_id, variant_id)
54
	if existing, ok := cart[key]; ok {
55
		existing.Quantity += quantity
56
		cart[key] = existing
57
	} else {
58
		cart[key] = Cart_Item{
59
			Product_ID: product_id,
60
			Variant_ID: variant_id,
61
			Quantity:   quantity,
62
		}
63
	}
64
	return cart
65
}
66
67
func Update_Cart_Quantity(cart Cart, product_id, variant_id, quantity int) Cart {
68
	key := cart_key(product_id, variant_id)
69
	if _, ok := cart[key]; ok {
70
		cart[key] = Cart_Item{
71
			Product_ID: product_id,
72
			Variant_ID: variant_id,
73
			Quantity:   quantity,
74
		}
75
	}
76
	return cart
77
}
78
79
func Remove_From_Cart(cart Cart, product_id, variant_id int) Cart {
80
	key := cart_key(product_id, variant_id)
81
	delete(cart, key)
82
	return cart
83
}
84
85
func Count_Cart_Items(cart Cart) int {
86
	total := 0
87
	for _, item := range cart {
88
		total += item.Quantity
89
	}
90
	return total
91
}
92
93
func Get_Cart_Items_With_Details(db *sql.DB, cart Cart) ([]Cart_Item_Detail, error) {
94
	var items []Cart_Item_Detail
95
96
	for _, item := range cart {
97
		variant, err := Get_Variant_By_ID(db, item.Variant_ID)
98
		if err != nil {
99
			return nil, err
100
		}
101
		if variant == nil {
102
			continue
103
		}
104
105
		items = append(items, Cart_Item_Detail{
106
			Product_ID: item.Product_ID,
107
			Variant_ID: item.Variant_ID,
108
			Quantity:   item.Quantity,
109
			Name:       variant.Product_Name,
110
			Size:       variant.Size,
111
			Price:      variant.Price,
112
			Image_URL:  variant.Image_URL,
113
			Subtotal:   variant.Price * item.Quantity,
114
		})
115
	}
116
117
	return items, nil
118
}
119
120
func Get_Cart_Total(items []Cart_Item_Detail) int {
121
	total := 0
122
	for _, item := range items {
123
		total += item.Subtotal
124
	}
125
	return total
126
}