-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy pathcart.js
More file actions
484 lines (410 loc) · 18.1 KB
/
cart.js
File metadata and controls
484 lines (410 loc) · 18.1 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
/*
* Copyright (c) 2024, Salesforce, Inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {getPromotionIdsForProduct} from '@salesforce/retail-react-app/app/utils/bonus-product/common'
import {findAvailableBonusDiscountLineItemIds} from '@salesforce/retail-react-app/app/utils/bonus-product/discovery'
import {isPickupShipment} from '@salesforce/retail-react-app/app/utils/shipment-utils'
/**
* Cart state operations and product relationship utilities for bonus products.
*
* This module handles functions that query, inspect, and manipulate existing cart state.
* It focuses on understanding relationships between products already in the cart,
* finding qualifying products, and managing cart item operations.
*
* Functions in this file:
* - Cart state queries (what's currently in cart)
* - Product relationship lookups (which products triggered which bonus items)
* - Cart item removal operations
* - Existing cart state inspection
*
* Note: This is different from discovery.js which finds NEW items to add to cart.
*/
/**
* Gets the qualifying product ID(s) for a bonus product from the bonusDiscountLineItems collection.
* This function matches bonus discount line items with qualifying products in the cart
* using the promotionId field.
*
* @param {Object} basket - The current basket/cart object
* @param {string} bonusDiscountLineItemId - The ID of the bonus discount line item to find qualifying products for
* @returns {Array<string>} - Array of qualifying product IDs that triggered this bonus item
*/
export const getQualifyingProductIdForBonusItem = (basket, bonusDiscountLineItemId) => {
if (!basket?.bonusDiscountLineItems || !basket?.productItems || !bonusDiscountLineItemId) {
return []
}
// Find the specific bonus discount line item
const bonusDiscountLineItem = basket.bonusDiscountLineItems.find(
(item) => item.id === bonusDiscountLineItemId
)
if (!bonusDiscountLineItem) {
return []
}
const promotionId = bonusDiscountLineItem.promotionId
// Find all products that have this promotion ID in their price adjustments
const qualifyingProductIds = []
basket.productItems.forEach((product) => {
if (product.priceAdjustments) {
const hasMatchingPromotion = product.priceAdjustments.some(
(adjustment) => adjustment.promotionId === promotionId
)
if (hasMatchingPromotion) {
qualifyingProductIds.push(product.productId)
}
}
})
return qualifyingProductIds
}
/**
* Gets bonus products allocated to a specific cart item using capacity-based sequential allocation.
* This function distributes available bonus products across qualifying cart items based on:
* - Individual item capacity (calculated from promotion rules and item quantity)
* - First-come-first-served allocation order (based on cart item position)
*
* @param {Object} basket - The current basket data
* @param {Object} targetCartItem - The specific cart item to get bonus products for
* @param {Object} productsWithPromotions - Products data with promotion info
* @returns {Array<Object>} Array of bonus products allocated to this specific cart item
*/
export const getBonusProductsForSpecificCartItem = (
basket,
targetCartItem,
productsWithPromotions
) => {
if (!basket || !targetCartItem || !productsWithPromotions) {
return []
}
const productId = targetCartItem.productId
// Get all available bonus products for this productId using existing function
const allBonusProducts = getBonusProductsInCartForProduct(
basket,
productId,
productsWithPromotions
)
if (allBonusProducts.length === 0) {
return []
}
// Find all qualifying cart items (non-bonus items with same productId)
const qualifyingCartItems =
basket.productItems?.filter(
(item) => item.productId === productId && !item.bonusProductLineItem
) || []
if (qualifyingCartItems.length <= 1) {
// If only one qualifying item, it gets all bonus products
return allBonusProducts
}
// Calculate total qualifying quantity across all items
const totalQualifyingQuantity = qualifyingCartItems.reduce(
(sum, item) => sum + (item.quantity || 1),
0
)
if (totalQualifyingQuantity === 0) {
return []
}
// Get promotion data to understand per-item capacity
const promotionIds = getPromotionIdsForProduct(basket, productId, productsWithPromotions)
const matchingDiscountItems =
basket.bonusDiscountLineItems?.filter((bonusItem) => {
return promotionIds.includes(bonusItem.promotionId)
}) || []
// Calculate total available capacity from promotion rules
const totalPromotionCapacity = matchingDiscountItems.reduce(
(sum, item) => sum + (item.maxBonusItems || 0),
0
)
// Create a flattened list of individual bonus product items for allocation
const bonusItemsToAllocate = []
allBonusProducts.forEach((aggregatedItem) => {
// Create individual items based on quantity
for (let i = 0; i < (aggregatedItem.quantity || 1); i++) {
bonusItemsToAllocate.push({
...aggregatedItem,
quantity: 1 // Each item represents 1 unit
})
}
})
// Sort qualifying items with composite priority:
// 1. Store pickup items first (higher priority for bonus product allocation)
// 2. Then by cart position (first-come-first-served within same delivery type)
//
// Rationale: Store pickup items are always shown first on the cart page. So we
// assign bonus products to them first.
const sortedQualifyingItems = [...qualifyingCartItems].sort((a, b) => {
// Get shipment information for both items
const aShipment = basket.shipments?.find((s) => s.shipmentId === a.shipmentId)
const bShipment = basket.shipments?.find((s) => s.shipmentId === b.shipmentId)
// Determine if items are store pickup or delivery
const aIsPickup = isPickupShipment(aShipment)
const bIsPickup = isPickupShipment(bShipment)
// Primary sort: Store pickup items first
if (aIsPickup && !bIsPickup) return -1 // a (pickup) comes before b (delivery)
if (!aIsPickup && bIsPickup) return 1 // b (pickup) comes before a (delivery)
// Secondary sort: Cart position within same delivery type
const aIndex = basket.productItems?.findIndex((item) => item.itemId === a.itemId) || 0
const bIndex = basket.productItems?.findIndex((item) => item.itemId === b.itemId) || 0
return aIndex - bIndex
})
// Allocate bonus items sequentially
let remainingBonusItems = [...bonusItemsToAllocate]
const allocations = new Map() // itemId -> allocated bonus items
for (const qualifyingItem of sortedQualifyingItems) {
if (remainingBonusItems.length === 0) break
// Calculate capacity for this specific item
// Capacity = (total promotion capacity / total qualifying quantity) * this item's quantity
const itemCapacity = Math.floor(
(totalPromotionCapacity / totalQualifyingQuantity) * (qualifyingItem.quantity || 1)
)
// Allocate up to itemCapacity bonus items to this qualifying item
const allocatedItems = remainingBonusItems.splice(0, itemCapacity)
allocations.set(qualifyingItem.itemId, allocatedItems)
}
// Return allocation for the target cart item
const targetAllocation = allocations.get(targetCartItem.itemId) || []
// Re-aggregate quantities for the same productId
const productQuantityMap = new Map()
targetAllocation.forEach((item) => {
const existingQuantity = productQuantityMap.get(item.productId) || 0
productQuantityMap.set(item.productId, existingQuantity + 1)
})
// Convert back to array format with aggregated quantities
const result = []
productQuantityMap.forEach((quantity, productId) => {
const sampleItem = targetAllocation.find((item) => item.productId === productId)
if (sampleItem) {
result.push({
...sampleItem,
quantity: quantity
})
}
})
return result
}
/**
* Gets all bonus products that are already in the cart for a specific product.
*
* @param {Object} basket - The current basket data
* @param {string} productId - The product ID to find bonus products for
* @param {Object} productsWithPromotions - Products data with promotion info
* @returns {Array<Object>} Array of bonus products in cart with aggregated quantities
*/
export const getBonusProductsInCartForProduct = (basket, productId, productsWithPromotions) => {
if (!basket || !productId || !productsWithPromotions) {
return []
}
// Get promotion IDs using enhanced product data
const productPromotionIds = getPromotionIdsForProduct(basket, productId, productsWithPromotions)
if (productPromotionIds.length === 0) {
return []
}
// Find bonus discount line items that match the promotion IDs
const matchingDiscountItems =
basket.bonusDiscountLineItems?.filter((bonusItem) => {
return productPromotionIds.includes(bonusItem.promotionId)
}) || []
if (matchingDiscountItems.length === 0) {
return []
}
// Get the discount line item IDs
const discountLineItemIds = matchingDiscountItems.map((item) => item.id)
// Find bonus products in cart that match these discount line item IDs
const bonusProductsInCart =
basket.productItems?.filter((item) => {
return (
item.bonusProductLineItem &&
discountLineItemIds.includes(item.bonusDiscountLineItemId)
)
}) || []
// Aggregate quantities for products with the same productId
const productQuantityMap = new Map()
bonusProductsInCart.forEach((item) => {
const existingQuantity = productQuantityMap.get(item.productId) || 0
productQuantityMap.set(item.productId, existingQuantity + (item.quantity || 0))
})
// Convert back to array format with aggregated quantities
const result = []
productQuantityMap.forEach((quantity, productId) => {
const sampleItem = bonusProductsInCart.find((item) => item.productId === productId)
result.push({
...sampleItem,
quantity: quantity
})
})
return result
}
/**
* Gets the qualifying product ID(s) for a bonus product that's already in the cart.
*
* @param {Object} basket - The current basket data
* @param {string} bonusProductId - The product ID of the bonus product in the cart
* @param {Object} productsWithPromotions - Products data with promotion info
* @returns {Array<string>} Array of qualifying product IDs that triggered this bonus product
*/
export const getQualifyingProductForBonusProductInCart = (
basket,
bonusProductId,
productsWithPromotions
) => {
// Validate inputs
if (!basket?.productItems || !bonusProductId || !productsWithPromotions) {
return []
}
// Find the bonus product in the cart
const bonusProduct = basket.productItems.find(
(item) => item.productId === bonusProductId && item.bonusProductLineItem === true
)
if (!bonusProduct) {
return []
}
// Get promotion IDs from the bonus product using enhanced data
const bonusPromotionIds = getPromotionIdsForProduct(
basket,
bonusProductId,
productsWithPromotions
)
if (bonusPromotionIds.length === 0) {
return []
}
// Find regular products (not bonus products) that have matching promotion IDs
const qualifyingProducts = basket.productItems.filter((item) => {
// Skip if this is a bonus product
if (item.bonusProductLineItem === true) {
return false
}
// Get promotion IDs for this product using enhanced data
const productPromotionIds = getPromotionIdsForProduct(
basket,
item.productId,
productsWithPromotions
)
return productPromotionIds.some((promotionId) => bonusPromotionIds.includes(promotionId))
})
return qualifyingProducts.map((product) => product.productId)
}
/**
* Finds all bonus product items in the basket that should be removed when a user clicks "Remove"
* on a specific bonus product. This includes all items with the same productId and from the same promotion,
* across all bonusDiscountLineItemIds.
*
* @param {Object} basket - The current basket data
* @param {Object} targetBonusProduct - The bonus product item that the user clicked "Remove" on
* @returns {Array} Array of bonus product items to remove (including the target item)
*/
export const findAllBonusProductItemsToRemove = (basket, targetBonusProduct) => {
if (!basket?.productItems || !targetBonusProduct || !targetBonusProduct.bonusProductLineItem) {
return []
}
// Find the bonusDiscountLineItem associated with the target product to get the promotionId
const targetBonusDiscountLineItem = basket.bonusDiscountLineItems?.find(
(item) => item.id === targetBonusProduct.bonusDiscountLineItemId
)
if (!targetBonusDiscountLineItem) {
// If we can't find the promotion, fall back to removing just this single item
return [targetBonusProduct]
}
const promotionId = targetBonusDiscountLineItem.promotionId
const productId = targetBonusProduct.productId
// Find all bonusDiscountLineItemIds for this promotion
const promotionBonusDiscountLineItemIds = (basket.bonusDiscountLineItems || [])
.filter((item) => item.promotionId === promotionId)
.map((item) => item.id)
// Find all bonus product items with the same productId and from the same promotion
const itemsToRemove = basket.productItems.filter((item) => {
return (
item.bonusProductLineItem &&
item.productId === productId &&
promotionBonusDiscountLineItemIds.includes(item.bonusDiscountLineItemId)
)
})
return itemsToRemove
}
/**
* Validates and caps the requested quantity based on maximum allowed
* @param {number} requestedQuantity - The quantity requested by user
* @param {number} maxAllowed - Maximum allowed quantity (can be null/undefined)
* @returns {number} - Validated and capped quantity (minimum 1)
*/
export const validateAndCapQuantity = (requestedQuantity, maxAllowed) => {
// Default quantity to 1 if not provided or invalid, ensure positive
let finalQuantity = Math.max(requestedQuantity || 1, 1)
// Cap quantity to remaining capacity (defensive programming)
if (maxAllowed && finalQuantity > maxAllowed) {
finalQuantity = maxAllowed
}
return finalQuantity
}
/**
* Distributes quantity across available bonus discount line items
* @param {number} quantity - Total quantity to distribute
* @param {Array<[string, number]>} availablePairs - Array of [bonusDiscountLineItemId, availableCapacity] pairs
* @returns {Array<{bonusDiscountLineItemId: string, quantity: number}>} - Distribution result
*/
export const distributeQuantityAcrossBonusItems = (quantity, availablePairs) => {
const distribution = []
let remainingQuantity = quantity
// Distribute quantity across available bonus discount line items
for (const [bonusDiscountLineItemId, availableCapacity] of availablePairs) {
if (remainingQuantity <= 0) {
break // All quantity has been distributed
}
// Calculate amount to add: minimum of remaining quantity and available capacity
const quantityToAdd = Math.min(remainingQuantity, availableCapacity)
distribution.push({
bonusDiscountLineItemId,
quantity: quantityToAdd
})
remainingQuantity -= quantityToAdd
}
return distribution
}
/**
* Builds product items from quantity distribution
* @param {Array<{bonusDiscountLineItemId: string, quantity: number}>} distribution - Quantity distribution
* @param {Object} variant - Product variant object
* @param {Object} product - Product object
* @returns {Array<Object>} - Array of product items ready for cart
*/
export const buildProductItemsFromDistribution = (distribution, variant, product) => {
return distribution.map(({bonusDiscountLineItemId, quantity}) => ({
productId: variant?.productId || product?.productId || product?.id,
price: variant?.price || product?.price,
quantity: parseInt(quantity, 10),
bonusDiscountLineItemId
}))
}
/**
* Processes products for bonus cart addition by validating quantities and distributing across available slots
* @param {Array} products - Array of {variant, quantity} objects
* @param {Object} basket - Current basket object
* @param {string} promotionId - The promotion ID
* @param {Object} product - The main product object
* @param {Function} getRemainingBonusQuantity - Function to get remaining bonus quantity
* @returns {Array<Object>} - Array of product items ready for cart
*/
export const processProductsForBonusCart = (
products,
basket,
promotionId,
product,
getRemainingBonusQuantity
) => {
const productItems = []
// Process each item in the selection
for (const {variant, quantity} of products) {
// Validate and cap quantity
const maxAllowed = getRemainingBonusQuantity()
const finalQuantity = validateAndCapQuantity(quantity, maxAllowed)
// Get list of available bonus discount line items with their capacities
const availablePairs = findAvailableBonusDiscountLineItemIds(basket, promotionId)
if (availablePairs.length === 0) {
continue // Skip this item but process others
}
// Distribute quantity across available bonus discount line items
const distribution = distributeQuantityAcrossBonusItems(finalQuantity, availablePairs)
// Build product items from distribution
const items = buildProductItemsFromDistribution(distribution, variant, product)
productItems.push(...items)
}
return productItems
}