+
Skip to content

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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ test("should call discount item function when discountType parameters is item",
discountType: "item"
}
};
applyItemDiscountToCart.mockReturnValueOnce({ cart: "cart", affected: "affected", reason: "reason" });
discountAction.handler(context, cart, params);
expect(applyItemDiscountToCart).toHaveBeenCalledWith(context, params, cart);
});
Expand All @@ -40,6 +41,7 @@ test("should call discount order function when discountType parameters is order"
discountType: "order"
}
};
applyOrderDiscountToCart.mockReturnValueOnce({ cart: "cart", affected: "affected", reason: "reason" });
discountAction.handler(context, cart, params);
expect(applyOrderDiscountToCart).toHaveBeenCalledWith(context, params, cart);
});
Expand All @@ -53,6 +55,7 @@ test("should call discount shipping function when discountType parameters is shi
discountType: "shipping"
}
};
applyShippingDiscountToCart.mockReturnValueOnce({ cart: "cart", affected: "affected", reason: "reason" });
discountAction.handler(context, cart, params);
expect(applyShippingDiscountToCart).toHaveBeenCalledWith(context, params, cart);
});
Expand Down
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;
}
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]);
});
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);
Copy link
Contributor

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 the actionHandler funcs of child plugins (ex packages/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

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;
}
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);
});
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;
}
Loading
点击 这是indexloc提供的php浏览器服务,不要输入任何密码和下载