-
Notifications
You must be signed in to change notification settings - Fork 4
/
i_price_adjustment.go
376 lines (305 loc) · 12.6 KB
/
i_price_adjustment.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package coupon
import (
"strings"
"time"
"github.com/ottemo/commerce/app/models/checkout"
"github.com/ottemo/commerce/db"
"github.com/ottemo/commerce/env"
"github.com/ottemo/commerce/utils"
)
// GetName returns the name of the current coupon implementation
func (it *Coupon) GetName() string {
return "Coupon"
}
// GetCode returns the code of the current coupon implementation
func (it *Coupon) GetCode() string {
return "coupon"
}
// GetPriority returns the code of the current coupon implementation
func (it *Coupon) GetPriority() []float64 {
baseCouponPriority := utils.InterfaceToFloat64(env.ConfigGetValue(ConstConfigPathDiscountApplyPriority))
cartCalculationPriority := baseCouponPriority + 0.01
return []float64{baseCouponPriority, cartCalculationPriority}
}
// Calculate calculates and returns a set of coupons applied to the provided checkout
func (it *Coupon) Calculate(checkoutInstance checkout.InterfaceCheckout, currentPriority float64) []checkout.StructPriceAdjustment {
var result []checkout.StructPriceAdjustment
// check session for applied coupon codes
if currentSession := checkoutInstance.GetSession(); currentSession != nil {
redeemedCodes := utils.InterfaceToStringArray(currentSession.Get(ConstSessionKeyCurrentRedemptions))
if len(redeemedCodes) > 0 {
// loading information about applied coupons
collection, err := db.GetCollection(ConstCollectionNameCouponDiscounts)
if err != nil {
return result
}
err = collection.AddFilter("code", "in", redeemedCodes)
if err != nil {
return result
}
records, err := collection.Load()
if err != nil || len(records) == 0 {
return result
}
applicableProductDiscounts := make(map[string][]discount)
applicableCartDiscounts := make([]discount, 0)
// collect products to one map, that holds productID: qty and used to get apply qty
productsInCart := make(map[string]int)
items := checkoutInstance.GetItems()
for _, productInCart := range items {
productID := productInCart.GetProductID()
productQty := productInCart.GetQty()
if qty, present := productsInCart[productID]; present {
productsInCart[productID] = qty + productQty
continue
}
productsInCart[productID] = productQty
applicableProductDiscounts[productID] = make([]discount, 0)
}
// use coupon map to hold the correct application order and ignore previously used coupons
discountCodes := make(map[string]map[string]interface{})
for _, record := range records {
discountsUsageQty := getCouponApplyQty(productsInCart, record)
discountCode := utils.InterfaceToString(record["code"])
if discountCode != "" && discountsUsageQty > 0 {
record["usage_qty"] = discountsUsageQty
discountCodes[discountCode] = record
}
}
couponPriorityValue := utils.InterfaceToFloat64(env.ConfigGetValue(ConstConfigPathDiscountApplyPriority))
productCouponsCalculation := couponPriorityValue == currentPriority
// accumulation of coupon discounts for cart to result and for products to applicableProductDiscounts
for appliedCodesIdx, discountCode := range redeemedCodes {
discountCoupon, present := discountCodes[discountCode]
if !present {
continue
}
validStart := isValidStart(discountCoupon["since"])
validEnd := isValidEnd(discountCoupon["until"])
// to be applicable coupon should satisfy following conditions:
// [begin] >= currentTime <= [end] if set
if !validStart || !validEnd {
// we have not applicable coupon - removing it from applied coupons list
newRedemptions := make([]string, 0, len(redeemedCodes)-1)
for idx, value := range redeemedCodes {
if idx != appliedCodesIdx {
newRedemptions = append(newRedemptions, value)
}
}
currentSession.Set(ConstSessionKeyCurrentRedemptions, newRedemptions)
continue
}
discountTarget := utils.InterfaceToString(discountCoupon["target"])
// add discount object for every product id that it can affect
applicableDiscount := discount{
Code: utils.InterfaceToString(discountCoupon["code"]),
Name: utils.InterfaceToString(discountCoupon["name"]),
Amount: utils.InterfaceToFloat64(discountCoupon["amount"]),
Percents: utils.InterfaceToFloat64(discountCoupon["percent"]),
Qty: utils.InterfaceToInt(discountCoupon["usage_qty"]),
}
// if we in product coupons calculation then skip cart coupons
if strings.Contains(discountTarget, checkout.ConstDiscountObjectCart) || discountTarget == "" {
if !productCouponsCalculation {
applicableCartDiscounts = append(applicableCartDiscounts, applicableDiscount)
}
continue
}
// collect only discounts for productIDs that are in cart
for _, productID := range utils.InterfaceToStringArray(discountTarget) {
if discounts, present := applicableProductDiscounts[productID]; present {
applicableProductDiscounts[productID] = append(discounts, applicableDiscount)
}
}
}
// handle cart coupon discounts to find one that is biggest and append it to result
// as price adjustments in % and in $ amount
if !productCouponsCalculation {
currentCartAmount := checkoutInstance.GetItemSpecificTotal(0, checkout.ConstLabelGrandTotal)
if len(applicableCartDiscounts) > 0 && currentCartAmount > 0 {
applicableDiscount, _ := findBiggestDiscount(applicableCartDiscounts, currentCartAmount)
currentPriceAdjustment := checkout.StructPriceAdjustment{
Code: applicableDiscount.Code,
Name: applicableDiscount.Name,
Amount: applicableDiscount.Percents * -1,
IsPercent: true,
Priority: currentPriority,
Labels: []string{checkout.ConstLabelDiscount},
PerItem: nil,
}
if applicableDiscount.Percents > 0 {
currentPriceAdjustment.Priority += float64(0.00001)
result = append(result, currentPriceAdjustment)
}
if applicableDiscount.Amount > 0 {
currentPriceAdjustment.Amount = applicableDiscount.Amount * -1
currentPriceAdjustment.IsPercent = false
currentPriceAdjustment.Priority += float64(0.0001)
result = append(result, currentPriceAdjustment)
}
}
return result
}
// hold price adjustment for every coupon code ( to make total details with right description)
priceAdjustments := make(map[string]checkout.StructPriceAdjustment)
// adding to discounts the biggest applicable discount per product
for _, cartItem := range checkoutInstance.GetDiscountableItems() {
index := utils.InterfaceToString(cartItem.GetIdx())
if cartProduct := cartItem.GetProduct(); cartProduct != nil {
productPrice := cartProduct.GetPrice()
productID := cartItem.GetProductID()
productQty := cartItem.GetQty()
// discount will be applied for every single product and grouped per item
for i := 0; i < productQty; i++ {
productDiscounts, present := applicableProductDiscounts[productID]
if !present || len(productDiscounts) <= 0 {
break
}
// looking for biggest applicable discount for current item
biggestAppliedDiscount, biggestAppliedDiscountIndex := findBiggestDiscount(productDiscounts, productPrice)
// update used discount and change qty of chosen discount to number of usage
discountUsed := productDiscounts[biggestAppliedDiscountIndex].Qty
if discountableProductsQty := productQty - i; discountableProductsQty < discountUsed {
discountUsed = discountableProductsQty
}
i += discountUsed - 1
productDiscounts[biggestAppliedDiscountIndex].Qty -= discountUsed
// remove fully used discount from discounts list
var newProductDiscounts []discount
for _, currentDiscount := range productDiscounts {
if currentDiscount.Qty > 0 {
newProductDiscounts = append(newProductDiscounts, currentDiscount)
}
}
applicableProductDiscounts[productID] = newProductDiscounts
// making from discount price adjustment
// calculating amount that will be discounted from item
amount := float64(discountUsed) * biggestAppliedDiscount.Total * -1
// add this amount to already existing PA (with the same coupon code) or creating new
if priceAdjustment, present := priceAdjustments[biggestAppliedDiscount.Code]; present {
priceAdjustment.PerItem[index] = utils.RoundPrice(priceAdjustment.PerItem[index] + amount)
priceAdjustments[biggestAppliedDiscount.Code] = priceAdjustment
} else {
currentPriority += float64(0.000001)
priceAdjustments[biggestAppliedDiscount.Code] = checkout.StructPriceAdjustment{
Code: biggestAppliedDiscount.Code,
Name: biggestAppliedDiscount.Name,
Amount: 0,
IsPercent: false,
Priority: currentPriority,
Labels: []string{checkout.ConstLabelDiscount},
PerItem: map[string]float64{
index: amount,
},
}
}
}
}
}
// attach price adjustments on products to result
for _, priceAdjustment := range priceAdjustments {
result = append(result, priceAdjustment)
}
}
}
return result
}
//finds biggest discount amount if applied more than one coupon
func findBiggestDiscount(discounts []discount, total float64) (discount, int) {
var biggestAppliedDiscount discount
var biggestAppliedDiscountIndex int
// looking for biggest applicable discount for current item
for index, discount := range discounts {
if (discount.Qty) > 0 {
productDiscountableAmount := discount.Amount + total*discount.Percents/100
// if we have discount that is bigger then a price we will apply it
if productDiscountableAmount > total {
biggestAppliedDiscount = discount
biggestAppliedDiscount.Total = total
biggestAppliedDiscountIndex = index
break
}
if biggestAppliedDiscount.Total < productDiscountableAmount {
biggestAppliedDiscount = discount
biggestAppliedDiscount.Total = productDiscountableAmount
biggestAppliedDiscountIndex = index
}
}
}
return biggestAppliedDiscount, biggestAppliedDiscountIndex
}
// check coupon limitation parameters for correspondence to current checkout values
// return qty of usages if coupon is allowed for current checkout and satisfies all conditions
func getCouponApplyQty(productsInCart map[string]int, couponDiscount map[string]interface{}) int {
result := -1
if limits, present := couponDiscount["limits"]; present {
limitations := utils.InterfaceToMap(limits)
if len(limitations) > 0 {
for limitingKey, limitingValue := range limitations {
switch strings.ToLower(limitingKey) {
case "product_in_cart":
requiredProduct := utils.InterfaceToStringArray(limitingValue)
for index, productID := range requiredProduct {
if _, present := productsInCart[productID]; present {
break
}
if index == (len(requiredProduct) - 1) {
return 0
}
}
case "products_in_cart":
requiredProducts := utils.InterfaceToStringArray(limitingValue)
for _, productID := range requiredProducts {
if _, present := productsInCart[productID]; !present {
return 0
}
}
case "products_in_qty":
requiredProducts := utils.InterfaceToMap(limitingValue)
for requiredProductID, requiredQty := range requiredProducts {
requiredQty := utils.InterfaceToInt(requiredQty)
if requiredQty < 1 {
requiredQty = 1
}
productQty, present := productsInCart[requiredProductID]
limitingQty := utils.InterfaceToInt(productQty / requiredQty)
if !present || limitingQty < 1 {
return 0
}
if result == -1 || limitingQty < result {
result = limitingQty
}
}
} // end of switch
} // end of loop
if maxLimitValue, present := limitations["max_usage_qty"]; present {
limitingQty := utils.InterfaceToInt(maxLimitValue)
if limitingQty > 0 && (result > limitingQty || result == -1) {
result = limitingQty
}
if result == -1 && limitingQty == -1 {
result = 9999
}
}
}
}
if result == -1 {
result = 1
}
return result
}
// validStart returns a boolean value of the datetame passed is valid
func isValidStart(start interface{}) bool {
couponStart := utils.InterfaceToTime(start)
currentTime := time.Now()
isValidStart := (utils.IsZeroTime(couponStart) || couponStart.Unix() <= currentTime.Unix())
return isValidStart
}
// validEnd returns a boolean value of the datetame passed is valid
func isValidEnd(end interface{}) bool {
couponEnd := utils.InterfaceToTime(end)
currentTime := time.Now()
// to be applicable coupon should satisfy following conditions:
isValidEnd := (utils.IsZeroTime(couponEnd) || couponEnd.Unix() >= currentTime.Unix())
return isValidEnd
}