-
Notifications
You must be signed in to change notification settings - Fork 2.2k
feat: stackability resolution strategy #6823
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
vanpho93
merged 1 commit into
feat/promotions-signed
from
feat/pick-the-best-combination-of-promotions
May 22, 2023
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
packages/api-plugin-promotions-discounts/src/handlers/getApplicablePromotions.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
import _ from "lodash"; | ||
import getPromotionCombinations from "./getPromotionCombinations.js"; | ||
import getHighestCombination from "./getHighestCombination.js"; | ||
|
||
|
||
/** | ||
* @summary get all applicable promotions | ||
* @param {*} context - The application context | ||
* @param {*} cart - The cart to apply the promotion to | ||
* @param {*} promotions - The promotions to apply | ||
* @returns {Promise<Array<Object>>} - An array of promotions | ||
*/ | ||
export default async function getApplicablePromotions(context, cart, promotions) { | ||
const promotionsWithoutShippingDiscount = _.filter(promotions, (promotion) => promotion.promotionType !== "shipping-discount"); | ||
const shippingPromotions = _.differenceBy(promotions, promotionsWithoutShippingDiscount, "_id"); | ||
|
||
const discountCalculationMethodOrder = ["flat", "percentage", "fixed", "none"]; | ||
const sortedPromotions = _.sortBy(promotionsWithoutShippingDiscount, (promotion) => { | ||
const method = promotion.actions[0]?.actionParameters?.discountCalculationMethod || "none"; | ||
return discountCalculationMethodOrder.indexOf(method); | ||
}); | ||
|
||
const promotionCombinations = await getPromotionCombinations(context, cart, sortedPromotions); | ||
const highestPromotions = await getHighestCombination(context, cart, promotionCombinations); | ||
const applicablePromotions = highestPromotions.concat(shippingPromotions); | ||
|
||
return applicablePromotions; | ||
} |
35 changes: 35 additions & 0 deletions
35
packages/api-plugin-promotions-discounts/src/handlers/getApplicablePromotions.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import mockContext from "@reactioncommerce/api-utils/tests/mockContext.js"; | ||
import getApplicablePromotions from "./getApplicablePromotions.js"; | ||
import getPromotionCombinations from "./getPromotionCombinations.js"; | ||
import getHighestCombination from "./getHighestCombination.js"; | ||
|
||
jest.mock("./getPromotionCombinations.js"); | ||
jest.mock("./getHighestCombination.js"); | ||
|
||
const promo1 = { _id: "1", promotionType: "order-discount", actions: [{ actionParameters: { discountCalculationMethod: "flat" } }] }; | ||
const promo2 = { _id: "2", promotionType: "item-discount", actions: [{ actionParameters: { discountCalculationMethod: "percentage" } }] }; | ||
const promo3 = { _id: "3", promotionType: "item-discount", actions: [{ actionParameters: { discountCalculationMethod: "fixed" } }] }; | ||
const promo4 = { _id: "4", promotionType: "order-discount", actions: [{ actionParameters: { discountCalculationMethod: "fixed" } }] }; | ||
const promo5 = { _id: "5", promotionType: "order-discount", actions: [{ actionParameters: { discountCalculationMethod: "flat" } }] }; | ||
const promo6 = { _id: "6", promotionType: "shipping-discount", actions: [{ actionParameters: { discountCalculationMethod: "flat" } }] }; | ||
|
||
test("getApplicablePromotions returns correct promotions", async () => { | ||
const promotions = [promo1, promo2, promo3, promo4, promo5, promo6]; | ||
|
||
const cart = { | ||
_id: "cartId" | ||
}; | ||
|
||
const highestPromotions = [promo1, promo3, promo4]; | ||
const combinations = [[promo1, promo2], [promo1, promo3, promo4], [promo5], [promo6]]; | ||
getPromotionCombinations.mockReturnValueOnce(combinations); | ||
getHighestCombination.mockReturnValueOnce(highestPromotions); | ||
|
||
const applicablePromotions = await getApplicablePromotions(mockContext, cart, promotions); | ||
|
||
const sortedPromotionsWithoutShippingDiscount = [promo1, promo5, promo2, promo3, promo4]; | ||
expect(getPromotionCombinations).toHaveBeenCalledWith(mockContext, cart, sortedPromotionsWithoutShippingDiscount); | ||
expect(getHighestCombination).toHaveBeenCalledWith(mockContext, cart, combinations); | ||
|
||
expect(applicablePromotions).toEqual([...highestPromotions, promo6]); | ||
}); |
37 changes: 37 additions & 0 deletions
37
packages/api-plugin-promotions-discounts/src/handlers/getHighestCombination.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import _ from "lodash"; | ||
|
||
/** | ||
* @summary get the total discount on the cart | ||
* @param {Object} cart - The cart to apply the promotion to | ||
* @returns {Number} - The total discount on the cart | ||
*/ | ||
function getTotalDiscountOnCart(cart) { | ||
return cart.items.map((item) => (item.subtotal.discount || 0)).reduce((pv, cv) => pv + cv, 0); | ||
} | ||
|
||
/** | ||
* @summary get the highest combination of promotions | ||
* @param {Object} context - The application context | ||
* @param {Object} cart - The cart to apply the promotion to | ||
* @param {Object} combinations - The combinations to compare | ||
* @returns {Promise<Array<Object>>} - The highest combination | ||
*/ | ||
export default async function getHighestCombination(context, cart, combinations) { | ||
const { promotions: { enhancers, utils } } = context; | ||
|
||
const tasks = combinations.map(async (combinationPromotions) => { | ||
let copiedCart = _.cloneDeep(cart); | ||
for (const promo of combinationPromotions) { | ||
// eslint-disable-next-line no-await-in-loop | ||
const { affected, temporaryAffected } = await utils.actionHandler(context, copiedCart, promo); | ||
if (!affected || temporaryAffected) continue; | ||
copiedCart = utils.enhanceCart(context, enhancers, copiedCart); | ||
} | ||
const totalDiscount = getTotalDiscountOnCart(copiedCart); | ||
return { totalDiscount, promotions: combinationPromotions }; | ||
}); | ||
const taskResults = await Promise.all(tasks); | ||
|
||
const highestResult = _.maxBy(taskResults, "totalDiscount"); | ||
return highestResult.promotions; | ||
} |
51 changes: 51 additions & 0 deletions
51
packages/api-plugin-promotions-discounts/src/handlers/getHighestCombination.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
import mockContext from "@reactioncommerce/api-utils/tests/mockContext.js"; | ||
import getHighestCombination from "./getHighestCombination.js"; | ||
|
||
|
||
test("should return the highest combination of promotions", async () => { | ||
const cart = { | ||
_id: "cartId", | ||
items: [ | ||
{ | ||
_id: "itemId", | ||
subtotal: { | ||
discount: 0 | ||
} | ||
}, | ||
{ | ||
_id: "itemId2", | ||
subtotal: { | ||
discount: 0 | ||
} | ||
} | ||
] | ||
}; | ||
|
||
const combinations = [ | ||
[ | ||
{ _id: "promo1", discount: 10 }, | ||
{ _id: "promo2", discount: 2 } | ||
], | ||
[ | ||
{ _id: "promo3", discount: 3 }, | ||
{ _id: "promo4", discount: 5 } | ||
] | ||
]; | ||
|
||
mockContext.promotions = { | ||
enhancers: [], | ||
utils: { | ||
enhanceCart: jest.fn().mockImplementation((_, __, _cart) => _cart), | ||
actionHandler: jest.fn().mockImplementation((context, _cart, promo) => { | ||
_cart.items.forEach((item) => { | ||
item.subtotal.discount += promo.discount; | ||
}); | ||
return { affected: true }; | ||
}) | ||
} | ||
}; | ||
|
||
const result = await getHighestCombination(mockContext, cart, combinations); | ||
const highestPromotions = combinations[0]; | ||
expect(result).toEqual(highestPromotions); | ||
}); |
55 changes: 55 additions & 0 deletions
55
packages/api-plugin-promotions-discounts/src/handlers/getPromotionCombinations.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
/* eslint-disable no-await-in-loop */ | ||
import _ from "lodash"; | ||
|
||
/** | ||
* @summary get the combination of promotions | ||
* @param {Object} context - The application context | ||
* @param {Object} cart - The cart to apply the promotion to | ||
* @param {Array<Object>} promotions - The promotions to apply | ||
* @returns {Promise<Object>} - The combination of promotions | ||
*/ | ||
export default async function getPromotionCombinations(context, cart, promotions) { | ||
const { promotions: { utils } } = context; | ||
|
||
const explicitPromotions = promotions.filter((promotion) => promotion.triggerType === "explicit"); | ||
const implicitPromotions = promotions.filter((promotion) => promotion.triggerType === "implicit"); | ||
|
||
const stack = [explicitPromotions]; | ||
let combinations = []; | ||
|
||
while (stack.length > 0) { | ||
const combination = stack.pop(); | ||
combinations.push(combination); | ||
|
||
const nextPosition = implicitPromotions.indexOf(_.last(combination)) + 1 || 0; | ||
// eslint-disable-next-line no-plusplus | ||
for (let position = nextPosition; position < implicitPromotions.length; position++) { | ||
const promotion = implicitPromotions[position]; | ||
const { qualifies } = await utils.canBeApplied(context, cart, { appliedPromotions: combination, promotion }); | ||
|
||
if (!stack.some((currentCombination) => currentCombination.length === 1 && currentCombination[0]._id === promotion._id)) { | ||
stack.push([promotion]); | ||
} | ||
|
||
if (qualifies) { | ||
const newCombination = [...combination, promotion]; | ||
stack.push(newCombination); | ||
continue; | ||
} | ||
} | ||
} | ||
|
||
// remove combination if is a subset of another combinations | ||
combinations = _.uniqWith(combinations, _.isEqual); | ||
|
||
combinations = _.filter( | ||
combinations, | ||
(combination) => | ||
!_.some(combinations, (anotherCombination) => { | ||
if (_.isEqual(combination, anotherCombination)) return false; | ||
return _.differenceBy(combination, anotherCombination, "_id").length === 0; | ||
}) | ||
); | ||
|
||
return combinations; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assume the return values
affected
&temporaryAffected
will be defined by theactionHandler
funcs of child plugins (expackages/api-plugin-promotions-discounts/src/discountTypes/order/applyOrderDiscountToCart.js
). I have not reviewed them now and will review while merging feat/promotions.Meanwhile, I could not find the field
temporaryAffected
being returned by any handler. only affected & reason were returned