-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply-discount.js
More file actions
691 lines (666 loc) · 26.2 KB
/
Copy pathapply-discount.js
File metadata and controls
691 lines (666 loc) · 26.2 KB
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
const ecomUtils = require('@ecomplus/utils')
const {
validateDateRange,
validateCustomerId,
checkOpenPromotion,
getValidDiscountRules,
matchDiscountRule,
matchFreebieRule,
mapCampaignProducts
} = require('../../../lib/helpers')
exports.post = ({ appSdk, admin }, req, res) => {
const { storeId } = req
// body was already pre-validated on @/bin/web.js
// treat module request body
const { params, application } = req.body
// app configured options
const config = Object.assign({}, application.data, application.hidden_data)
if (config.advanced && typeof config.advanced === 'object') {
Object.assign(config, config.advanced)
}
// setup response object
// https://apx-mods.e-com.plus/api/v1/apply_discount/response_schema.json?store_id=100
const response = { _cf: 1 }
const discountPerSku = {}
const respondSuccess = () => {
if (response.available_extra_discount && !response.available_extra_discount.value) {
delete response.available_extra_discount
}
if (response.discount_rule) {
if (!response.discount_rule.extra_discount?.value) {
delete response.discount_rule
} else if (!response.discount_rule.description && config.describe_discounted_items) {
const discountedSkus = Object.keys(discountPerSku)
if (discountedSkus.length) {
response.discount_rule.description = `
Descontos por SKU:
---
${discountedSkus.map((sku) => `\n${sku}: ${discountPerSku[sku].toFixed(2)}`)}
`.substring(0, 999)
}
}
}
res.send(response)
}
const checkUsageLimit = async (discountRule, label) => {
const { customer } = params
if (!label) {
label = discountRule.label
}
if (
label &&
customer && (customer._id || customer.doc_number) &&
(discountRule.usage_limit > 0 || discountRule.total_usage_limit > 0)
) {
// list orders to check discount usage limits
const url = '/orders.json?fields=status' +
`&extra_discount.app.label${(discountRule.case_insensitive ? '%=' : '=')}` +
encodeURIComponent(label)
const usageLimits = [{
// limit by customer
query: customer.doc_number
? `&buyers.doc_number=${customer.doc_number}`
: `&buyers._id=${customer._id}`,
max: discountRule.usage_limit
}, {
// total limit
query: '',
max: discountRule.total_usage_limit
}]
const auth = await appSdk.getAuth(storeId)
for (let i = 0; i < usageLimits.length; i++) {
const { query, max } = usageLimits[i]
if (max) {
// send Store API request to list orders with filters
const { response } = await appSdk.apiRequest(storeId, `${url}${query}`, 'GET', null, auth)
const countOrders = response.data.result
.filter(({ status }) => status !== 'cancelled')
.length
if (countOrders >= max) {
// limit reached
return false
}
}
}
}
return true
}
const getDiscountValue = (discount, maxDiscount) => {
let value
if (typeof maxDiscount !== 'number') {
const applyAt = discount.apply_at || 'total'
maxDiscount = params.amount[applyAt]
if (applyAt === 'total' && response.discount_rule) {
maxDiscount -= response.discount_rule.extra_discount.value
}
if (applyAt !== 'freight') {
const { value } = getFreebiesPreview()
maxDiscount -= value
}
}
if (maxDiscount > 0) {
// update amount discount and total
if (discount.type === 'percentage') {
value = maxDiscount * discount.value / 100
} else {
value = discount.value
}
if (value > maxDiscount) {
value = maxDiscount
}
}
return value
}
const addDiscount = (discount, flag, label, maxDiscount) => {
const value = getDiscountValue(discount, maxDiscount)
if (value) {
if (response.discount_rule) {
// accumulate discount
const extraDiscount = response.discount_rule.extra_discount
extraDiscount.value += value
if (extraDiscount.flags.length < 20) {
extraDiscount.flags.push(flag)
}
} else {
response.discount_rule = {
label: label || flag,
extra_discount: {
value,
flags: [flag]
}
}
}
return value
}
return null
}
const pointDiscountToSku = (discountValue, sku) => {
if (!discountValue || !sku) return
if (!discountPerSku[sku]) discountPerSku[sku] = 0
discountPerSku[sku] += discountValue
}
const pointDiscountToEachItem = (discountValue, filteredItems) => {
const itemsAmount = filteredItems.reduce(
(amount, item) => amount + (ecomUtils.price(item) * (item.quantity || 1)),
0
)
const discountMultiplier = discountValue / itemsAmount
filteredItems.forEach((item) => {
const discountPerItem = discountMultiplier * (ecomUtils.price(item) * (item.quantity || 1))
return pointDiscountToSku(discountPerItem, item.sku)
})
}
const getFreebiesPreview = () => {
if (params.items && params.items.length) {
// gift products (freebies) campaings
if (Array.isArray(config.freebies_rules)) {
const validFreebiesRules = config.freebies_rules.filter(rule => {
return validateDateRange(rule) &&
validateCustomerId(rule, params) &&
mapCampaignProducts({ product_ids: rule.check_product_ids }, params).valid &&
Array.isArray(rule.product_ids) &&
rule.product_ids.length &&
matchFreebieRule(rule, params)
})
if (validFreebiesRules) {
const cumulativeRules = []
let bestRule
let discountValue = 0
for (let i = 0; i < validFreebiesRules.length; i++) {
const rule = validFreebiesRules[i]
let subtotal = 0
const subtotalItems = []
params.items.forEach(item => {
if (Array.isArray(rule.category_ids)) {
if (Array.isArray(item.categories)) {
for (let i = 0; i < item.categories.length; i++) {
const category = item.categories[i]
if (rule.category_ids.indexOf(category._id) > -1) {
subtotal += (item.quantity * ecomUtils.price(item))
subtotalItems.push(item)
break
}
}
}
return
}
subtotal += (item.quantity * ecomUtils.price(item))
subtotalItems.push(item)
})
if (subtotal <= 0) {
continue
}
// start calculating discount
let value = 0
let fixedSubtotal = subtotal
rule.product_ids.forEach(productId => {
const item = params.items.find(item => productId === item.product_id)
if (item) {
const price = ecomUtils.price(item)
value += price
if (subtotalItems.find(item => productId === item.product_id)) {
fixedSubtotal -= price
}
}
})
if (rule.deduct_discounts) {
if (response.discount_rule) {
fixedSubtotal -= response.discount_rule.extra_discount.value
}
if (params.amount.discount) {
fixedSubtotal -= params.amount.discount
}
}
if (rule.cumulative_freebie === true && !(rule.min_subtotal > fixedSubtotal)) {
cumulativeRules.push({ rule, value })
}
if (!bestRule || value > discountValue || bestRule.min_subtotal < rule.min_subtotal) {
if (!(rule.min_subtotal > fixedSubtotal)) {
bestRule = rule
discountValue = value
} else if (!discountValue && fixedSubtotal >= rule.min_subtotal) {
// discount not applicable yet but additional freebies are available
bestRule = rule
}
}
}
if (bestRule) {
// provide freebie products \o/
response.freebie_product_ids = bestRule.product_ids
if (discountValue) {
if (bestRule.cumulative_freebie === true) {
cumulativeRules.forEach(({ rule, value }) => {
for (let i = 0; i < response.freebie_product_ids.length; i++) {
const productId = response.freebie_product_ids[i]
if (rule.product_ids.includes(productId)) {
// ignoring cumulative freebie rules with repeated products
return
}
}
discountValue += value
rule.product_ids.forEach((productId) => {
response.freebie_product_ids.push(productId)
})
})
}
return {
value: discountValue,
label: bestRule.label
}
}
}
}
}
}
return { value: 0 }
}
const addFreebies = () => {
const { value, label } = getFreebiesPreview()
if (value) {
const maxDiscount = Math.min(value, params.amount.total || 0)
addDiscount(
{ type: 'fixed', value },
'FREEBIES',
label,
maxDiscount
)
}
}
(async () => {
if (params.items && params.items.length) {
// try product kit discounts first
if (Array.isArray(config.product_kit_discounts)) {
config.product_kit_discounts = config.product_kit_discounts.map(kitDiscount => {
if (!kitDiscount.product_ids) {
// kit with any items (or per category)
kitDiscount.product_ids = []
}
return kitDiscount
})
}
const kitDiscounts = getValidDiscountRules(config.product_kit_discounts, params, params.items)
.sort((a, b) => {
if (!Array.isArray(a.product_ids) || !a.product_ids.length) {
if (Array.isArray(b.product_ids) && b.product_ids.length) {
return 1
}
}
if (a.min_quantity > b.min_quantity) {
return -1
} else if (b.min_quantity > a.min_quantity) {
return 1
} else if (a.discount.min_amount > b.discount.min_amount) {
return -1
} else if (b.discount.min_amount > a.discount.min_amount) {
return 1
}
return 0
})
// prevent applying duplicated kit discount for same items
let discountedItemIds = []
// check buy together recommendations
const buyTogether = []
for (let index = 0; index < kitDiscounts.length; index++) {
const kitDiscount = kitDiscounts[index]
if (kitDiscount) {
const productIds = Array.isArray(kitDiscount.product_ids)
? kitDiscount.product_ids
: []
const categoryIds = Array.isArray(kitDiscount.category_ids)
? kitDiscount.category_ids
: []
let kitItems = []
if (productIds.length) {
kitItems = params.items.filter(item => productIds.indexOf(item.product_id) > -1)
} else if (categoryIds.length) {
kitItems = params.items.filter(item => {
if (Array.isArray(item.categories)) {
for (let i = 0; i < item.categories.length; i++) {
const category = item.categories[i]
if (categoryIds.indexOf(category._id) > -1) {
return true
}
}
}
return false
})
} else {
kitItems = [...params.items]
}
kitItems = kitItems.filter(item => {
return item.quantity && discountedItemIds.indexOf(item.product_id) === -1
})
if (!kitItems.length) {
continue
}
const recommendBuyTogether = () => {
if (
params.items.length === 1 &&
productIds.length <= 4 &&
buyTogether.length < 300
) {
const baseProductId = params.items[0].product_id
if (productIds.indexOf(baseProductId) === -1) {
return
}
const baseItemQuantity = params.items[0].quantity || 1
const perItemQuantity = kitDiscount.min_quantity > 2
? Math.max(kitDiscount.min_quantity / (productIds.length - 1) - baseItemQuantity, 1)
: 1
const buyTogetherProducts = {}
productIds.forEach((productId) => {
if (productId !== baseProductId) {
buyTogetherProducts[productId] = perItemQuantity
}
})
if (Object.keys(buyTogetherProducts).length) {
buyTogether.push({
products: buyTogetherProducts,
discount: {
type: kitDiscount.originalDiscount?.type || kitDiscount.discount.type,
value: kitDiscount.originalDiscount?.value || kitDiscount.discount.value
}
})
}
}
}
const discount = Object.assign({}, kitDiscount.discount)
if (kitDiscount.min_quantity > 0) {
// check total items quantity
if (kitDiscount.same_product_quantity) {
kitItems = kitItems.filter(item => item.quantity >= kitDiscount.min_quantity)
} else {
let totalQuantity = 0
kitItems.forEach(({ quantity }) => {
totalQuantity += quantity
})
if (totalQuantity < kitDiscount.min_quantity) {
if (productIds.length > 1 && kitDiscount.check_all_items !== false) {
recommendBuyTogether()
}
continue
}
if (
discount.type === 'fixed' &&
kitDiscount.cumulative_discount !== false &&
!kitDiscount.usage_limit
) {
discount.value *= Math.floor(totalQuantity / kitDiscount.min_quantity)
}
}
}
if (
!params.amount ||
!(discount.min_amount > params.amount.total - getFreebiesPreview().value)
) {
if (kitDiscount.check_all_items !== false) {
let isSkip = false
for (let i = 0; i < productIds.length; i++) {
const productId = productIds[i]
if (productId && !kitItems.find(item => item.quantity && item.product_id === productId)) {
// product not on current cart
recommendBuyTogether()
isSkip = true
break
}
}
if (categoryIds.length) {
for (let i = 0; i < kitItems.length; i++) {
const { categories } = kitItems[i]
let hasListedCategory = false
if (categories) {
for (let i = 0; i < categories.length; i++) {
const category = categories[i]
if (categoryIds.find(categoryId => categoryId === category._id)) {
hasListedCategory = true
continue
}
}
}
if (!hasListedCategory) {
recommendBuyTogether()
isSkip = true
break
}
}
}
if (isSkip) continue
}
try {
const isAvailable = await checkUsageLimit(kitDiscount)
if (isAvailable) {
// apply cumulative discount \o/
if (kitDiscount.same_product_quantity) {
kitItems.forEach((item, i) => {
const discountValue = addDiscount(
discount,
`KIT-${(index + 1)}-${i}`,
kitDiscount.label,
ecomUtils.price(item) * (item.quantity || 1)
)
pointDiscountToSku(discountValue, item.sku)
})
} else {
const discountValue = addDiscount(discount, `KIT-${(index + 1)}`, kitDiscount.label)
pointDiscountToEachItem(discountValue, kitItems)
}
discountedItemIds = discountedItemIds.concat(kitItems.map(item => item.product_id))
}
} catch (err) {
console.error(`CANT_CHECK_USAGE_LIMITS store #${storeId}:`, err)
return res.status(409).send({
error: 'CANT_CHECK_USAGE_LIMITS',
message: err.message
})
}
}
}
}
if (buyTogether.length) {
response.buy_together = buyTogether
}
}
// additional discount coupons for API manipualation with
// PATCH https://api.e-com.plus/v1/applications/<discounts_app_id>/hidden_data.json { COUPON }
if (!config.discount_rules) {
config.discount_rules = []
}
Object.keys(config).forEach((configField) => {
switch (configField) {
case 'freebies_rules':
case 'product_kit_discounts':
case 'discount_rules':
return
}
const configObj = config[configField]
if (configObj && configObj.discount) {
config.discount_rules.push({
...configObj,
discount_coupon: configField
})
}
})
const discountRules = getValidDiscountRules(config.discount_rules, params)
if (discountRules.length) {
let { discountRule, discountMatchEnum } = matchDiscountRule(discountRules, params)
if (discountRule) {
// If primary is a freight open promotion but freight=0 (shipping not yet selected),
// prefer a non-freight primary so subtotal discounts can still be applied
if (
checkOpenPromotion(discountRule) &&
discountRule.discount.apply_at === 'freight' &&
!(params.amount && params.amount.freight)
) {
const { discountRule: altRule, discountMatchEnum: altEnum } = matchDiscountRule(discountRules, params, 'freight')
if (altRule) {
discountRule = altRule
discountMatchEnum = altEnum
}
}
const {
valid: isValidByItems,
items: filteredItems
} = mapCampaignProducts(discountRule, params)
if (!isValidByItems) {
addFreebies()
response.invalid_coupon_message = params.lang === 'pt_br'
? 'Nenhum produto da promoção está incluído no carrinho'
: 'No promotion products are included in the cart'
return respondSuccess()
}
const excludedProducts = discountRule.excluded_product_ids
if (Array.isArray(excludedProducts) && excludedProducts.length && params.items) {
// must check any excluded product is on cart
for (let i = 0; i < params.items.length; i++) {
const item = params.items[i]
if (item.quantity && excludedProducts.includes(item.product_id)) {
addFreebies()
response.invalid_coupon_message = params.lang === 'pt_br'
? `Promoção é inválida para o produto ${item.name}`
: `Invalid promotion for product ${item.name}`
return respondSuccess()
}
}
}
let { label, discount } = discountRule
if (typeof label !== 'string' || !label) {
label = params.discount_coupon || `DISCOUNT ${discountMatchEnum}`
}
if (
discount.apply_at !== 'freight' &&
(!response.available_extra_discount || !response.available_extra_discount.value ||
discountRule.default_discount === true || checkOpenPromotion(discountRule))
) {
// show current discount rule as available discount to apply
response.available_extra_discount = {
label: label.substring(0, 50)
}
;['min_amount', 'type', 'value'].forEach(field => {
if (discount[field]) {
response.available_extra_discount[field] = discount[field]
}
})
}
// params object follows list payments request schema:
// https://apx-mods.e-com.plus/api/v1/apply_discount/schema.json?store_id=100
let checkAmount
if (params.amount) {
checkAmount = params.amount[discountRule.discount.amount_field || 'total']
if (discountRule.discount.amount_field !== 'freight') checkAmount -= getFreebiesPreview().value
}
if (
params.amount && params.amount.total > 0 &&
!(discountRule.discount.min_amount > checkAmount)
) {
if (
discountRule.cumulative_discount === false &&
(response.discount_rule || params.amount.discount)
) {
if (
response.discount_rule?.extra_discount &&
!params.amount.discount &&
getDiscountValue(discount) > response.discount_rule.extra_discount.value
) {
// replace discount with new bigger one
delete response.discount_rule
} else {
// explain discount can't be applied :(
// https://apx-mods.e-com.plus/api/v1/apply_discount/response_schema.json?store_id=100
addFreebies()
response.invalid_coupon_message = params.lang === 'pt_br'
? 'A promoção não pôde ser aplicada porque este desconto não é cumulativo'
: 'This discount is not cumulative'
return respondSuccess()
}
}
// we have a discount to apply \o/
const discountValue = addDiscount(discountRule.discount, discountMatchEnum)
if (discountValue) {
if (filteredItems?.length) {
pointDiscountToEachItem(discountValue, filteredItems)
}
// add discount label and description if any
response.discount_rule.label = label
if (discountRule.description) {
response.discount_rule.description = discountRule.description
}
const trySecondaryDiscount = (secondaryParams, skipApplyAt) => {
const {
discountRule: secondDiscountRule,
discountMatchEnum: secondDiscountMatchEnum
} = matchDiscountRule(discountRules, secondaryParams, skipApplyAt)
if (secondDiscountRule) {
let checkAmount = params.amount[secondDiscountRule.discount.amount_field || 'total']
if (secondDiscountRule.discount.amount_field !== 'freight') checkAmount -= getFreebiesPreview().value
if (
secondDiscountRule.cumulative_discount !== false &&
!(secondDiscountRule.discount.min_amount > checkAmount)
) {
const applied = addDiscount(secondDiscountRule.discount, secondDiscountMatchEnum + '-2')
if (applied) return secondDiscountRule.discount.apply_at || 'total'
}
}
return null
}
const openItemsParams = {
items: params.items,
amount: params.amount,
domain: params.domain,
customer: params.customer
}
if (!checkOpenPromotion(discountRule)) {
let appliedSecondaryApplyAt = null
if (discountRule.cumulative_discount !== false) {
// when primary was matched by coupon/UTM, search open promotions for different amount
appliedSecondaryApplyAt = trySecondaryDiscount(openItemsParams, discountRule.discount.apply_at || 'total')
}
// check for additional open discount (skip secondary's apply_at to avoid double application)
const {
discountRule: openDiscountRule,
discountMatchEnum: openDiscountMatchEnum
} = matchDiscountRule(discountRules, openItemsParams, appliedSecondaryApplyAt)
if (
openDiscountRule &&
openDiscountRule.cumulative_discount !== false &&
openDiscountRule.discount.min_amount
) {
let checkAmount = params.amount[openDiscountRule.discount.amount_field || 'total']
if (checkAmount) {
// subtract current discount to validate cumulative open discount min amount
if (response.discount_rule) checkAmount -= response.discount_rule.extra_discount.value
if (openDiscountRule.discount.amount_field !== 'freight') checkAmount -= getFreebiesPreview().value
if (openDiscountRule.discount.min_amount <= checkAmount) {
addDiscount(openDiscountRule.discount, openDiscountMatchEnum)
}
}
}
} else if (discountRule.cumulative_discount !== false) {
// when primary is an open promotion, also check for secondary open discount with different amount
trySecondaryDiscount(params, discountRule.discount.apply_at || 'total')
}
try {
const isAvailable = await checkUsageLimit(discountRule, label)
if (!isAvailable) {
delete response.discount_rule
response.invalid_coupon_message = params.lang === 'pt_br'
? 'A promoção não pôde ser aplicada porque já atingiu o limite de usos'
: 'The promotion could not be applied because it has already reached the usage limit'
}
addFreebies()
return respondSuccess()
} catch (err) {
console.error(`CANT_CHECK_USAGE_LIMITS store #${storeId}:`, err)
return res.status(409).send({
error: 'CANT_CHECK_USAGE_LIMITS',
message: err.message
})
}
}
}
}
}
addFreebies()
// response with no error nor discount applied
respondSuccess()
})()
}