/
cart_item_query.go
64 lines (57 loc) · 1.65 KB
/
cart_item_query.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
package aggregate
import (
"encoding/json"
"github.com/8treenet/freedom/example/fshop/domain/entity"
)
//CartItemQuery 购物车项查询聚合根
type CartItemQuery struct {
entity.User
allCart []*entity.Cart
goodsMap map[int]*entity.Goods
}
// VisitAllItem 读取全部商品
func (query *CartItemQuery) VisitAllItem(f func(id, goodsId int, goodsName string, goodsNum, totalPrice int)) {
for i := 0; i < len(query.allCart); i++ {
goodsEntity := query.goodsMap[query.allCart[i].GoodsID]
f(query.allCart[i].ID, goodsEntity.ID, goodsEntity.Name, query.allCart[i].Num, query.allCart[i].Num*goodsEntity.Price)
}
}
// AllItemTotalPrice 全部商品总价
func (query *CartItemQuery) AllItemTotalPrice() (totalPrice int) {
for i := 0; i < len(query.allCart); i++ {
goodsEntity := query.goodsMap[query.allCart[i].GoodsID]
totalPrice += query.allCart[i].Num * goodsEntity.Price
}
return
}
// MarshalJSON .
func (query *CartItemQuery) MarshalJSON() ([]byte, error) {
var obj struct {
TotalPrice int //总价
Items []struct {
ID int //购物车项ID
GoodsID int //商品id
GoodsName string //商品名称
GoodsNum int //商品数量
TotalPrice int //商品价格
}
}
obj.TotalPrice = query.AllItemTotalPrice()
for i := 0; i < len(query.allCart); i++ {
goodsEntity := query.goodsMap[query.allCart[i].GoodsID]
obj.Items = append(obj.Items, struct {
ID int
GoodsID int
GoodsName string
GoodsNum int
TotalPrice int
}{
query.allCart[i].ID,
goodsEntity.ID,
goodsEntity.Name,
query.allCart[i].Num,
query.allCart[i].Num * goodsEntity.Price,
})
}
return json.Marshal(obj)
}