/
cart.go
66 lines (56 loc) · 1.41 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
package model
type CartBook struct {
ID uint64
Name, Author string
Quantity uint
Price, Subtotal float64
}
type CartBooks = []CartBook
func AddCartItem(userID, bookID uint64) error {
tx, err := db.Begin()
if err != nil {
return err
}
query := "insert ignore into cart(user_id, book_id) values(?, ?)"
result, err := tx.Exec(query, userID, bookID)
if err != nil {
return err
}
if count, _ := result.RowsAffected(); count == 0 {
query = `update cart
set quantity = quantity + 1
where user_id = ? and book_id = ?`
tx.Exec(query, userID, bookID)
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func GetCartItems(userID uint64) (books CartBooks) {
query := `select id, name, author, price, quantity, price * quantity
from book, cart
where id = book_id
and not deleted
and user_id = ?`
rs, _ := db.Query(query, userID)
defer rs.Close()
for book := (CartBook{}); rs.Next(); books = append(books, book) {
rs.Scan(&book.ID, &book.Name, &book.Author, &book.Price, &book.Quantity, &book.Subtotal)
}
return
}
func UpdateCartItem(userID, bookID uint64, quantity uint) (err error) {
if quantity == 0 {
query := `delete from cart
where user_id =? and book_id = ?`
_, err = db.Exec(query, userID, bookID)
} else {
query := `update cart
set quantity = ?
where user_id = ? and book_id = ?`
_, err = db.Exec(query, quantity, userID, bookID)
}
return
}