-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiscount.go
88 lines (80 loc) · 2.1 KB
/
discount.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
package receipt
import (
"encoding/json"
"log"
)
const (
_ = iota
DiscountPercentage95
DiscountBuy2Free1
)
var discountType = map[int]DiscountType{
DiscountPercentage95: &DiscountPercentage{"九五折", 0.95, 0},
DiscountBuy2Free1: &DiscountFree{"买二赠一", 3, 1},
}
// 当前折扣信息缓存
var Discounts map[int]*Discount
type Discount struct {
id int
disabled []int
productIds map[ProductId]bool
DiscountType
}
func (d *Discount) satisfied(item *item) bool {
if d.productIds[item.Product.Id] && d.DiscountType.satisfied(item) {
return true
}
return false
}
func checkConflict(discounts map[int]*Discount, dids []int, id int) bool {
discount, ok := discounts[id]
if !ok {
return false
}
dids = append(dids, id)
for _, did := range discount.disabled {
if _, ok := discounts[did]; ok {
if dids[0] == did {
return true
}
if Discounts[did].disabled != nil {
copies := make([]int, len(dids)+1)
copy(dids, copies)
copies = append(copies, did)
return checkConflict(discounts, copies, did)
} else {
return false
}
}
}
return false
}
func LoadDiscounts() {
Discounts = make(map[int]*Discount)
rows, _ := db.Query("SELECT id, discounttype, disabled, productids FROM discount")
for rows.Next() {
var id, discounttype int
var disabled, productids []byte
rows.Scan(&id, &discounttype, &disabled, &productids)
var discountIds, productIds []int
if len(disabled) > 0 {
if err := json.Unmarshal(disabled, &discountIds); err != nil {
log.Printf("field disabled json decode error '%s' with discount %d", err, id)
continue
}
}
if len(productids) > 0 {
if err := json.Unmarshal(productids, &productIds); err != nil {
log.Printf("field productids json decode error '%s' with discount %d", err, id)
continue
}
}
productIdSet := make(map[ProductId]bool, len(productIds))
for _, productid := range productIds {
productIdSet[ProductId(productid)] = true
}
discount := &Discount{id: id, disabled: discountIds, productIds: productIdSet}
discount.DiscountType = discountType[discounttype]
Discounts[id] = discount
}
}