function calculatePromotion(
body: { subOrders: Array<{ id: string; price: number }> },
params: {
purchasedProductIds: string[]; // An array containing the IDs of products eligible for discounts upon purchase.
discountProductsToBeAppliedIds: string[]; // An array containing the IDs of the products on which the discount will be applied.
discountedProductPrice: number; // The discounted price to be applied for each product.
},
context:{ promotionId: string, // The ID of the promotion that you do not want to be applied again when recalculated from a previous calculation.
userTransactions?: any[], // Data such as user's past transactions and the number of times the promotion has been used can be found.
couponGiftAmount?: number // The entered gift amount on the coupon, if available, is checked for applicability and applied.
},
) {
const purchasedProducts = body.subOrders.filter((s) =>
params.purchasedProductIds.includes(s.id) // Filtering the 'subOrders' array to include only the purchased products based on their IDs.
);
let totalDiscountAmount = 0; // Initialize the variable to hold the total discount amount.
const discountProductsToBeApplied = body.subOrders.filter((s) =>
params.discountProductsToBeAppliedIds.includes(s.id) // Filtering the 'subOrders' array to include only the discounted products based on their IDs.
);
const countOfDiscountProduct = discountProductsToBeApplied.length <= purchasedProducts.length ? discountProductsToBeApplied.length : purchasedProducts.length; // Determine the number of discounted products based on the minimum of either the existing discounted products or the purchased products.
for (let i = 0; i < countOfDiscountProduct; i++) { // Enter a loop for the number of discounted products.
totalDiscountAmount = countOfDiscountProduct * (discountProductsToBeApplied[i].price - params.discountedProductPrice); //Calculate the total discount amount by multiplying the number of discounted products by the difference between the product price and the discounted price.
}
return totalDiscountAmount; // Return the total discount amount.
}
// The 'body' object represents the 'subOrders' data, which contains many products with 'id' and 'price' properties.
const body = {
subOrders: [
{
id: '1',
price: 100,
},
{
id: '2',
price: 150,
},
{
id: '3',
price: 150,
},
{
id: '4',
price: 150,
},
]
};
const params = {
purchasedProductIds: ['1', '2'], // An array containing the IDs of the purchased products.
discountedProductPrice: 50, // The discounted price applied to each product.
discountProductsToBeAppliedIds: ['3', '4'] // An array containing the IDs of the products where the discount will be applied.
};
// Result: With the existing parameters, a total discount of 200 TL is returned based on the purchase of two X products, where, if available, the price of two Y products is set to Z TL each.
console.log(calculatePromotion(body, params));