Mircate
  1. How to
Mircate
  • Introduction
  • Authentication
  • Errors
  • Change Logs
  • PIM
    • Get Products
      POST
    • Get Product Settings
      GET
    • Get Catalog Settings
      GET
    • Upsert Product
      POST
    • Upsert Category
      POST
    • Bulk Product Upsert
      POST
    • Check Batch Status
      POST
    • Delete Product
      POST
    • Attach Product Attribute Image
      POST
    • Attach Category Image
      POST
    • Get Image
      GET
    • Upsert Attributes
      POST
    • Delete Attribute
      POST
    • Upsert Attribute Options
      POST
    • Upsert Attribute Option
      POST
    • Delete Attribute Option
      POST
  • Promotion
    • Calculate
      POST
    • Start Transaction
      POST
    • Commit Transaction
      POST
    • Revert Transaction
      POST
    • Cancel Transaction
      POST
    • Get Active Promotions
      GET
  • Loyalty
    • Receive Event
    • Calculate
    • Start Transaction
    • Commit Transaction
    • Cancel Transaction
    • List Measurements
  • Wallet
    • Get Wallet
    • Create Wallet
    • Create Account
    • Get Account
    • Get Accounts
    • List Accounts
    • List Transactions
    • Add Account
    • Remove Account
    • Fix
    • Load
    • Spend
    • Refund
    • Cancel
  • Talking Product
    • Create Product
    • Update Product
    • Delete Product
    • Get Product
    • List Product
  • Merchant
    • Sales Channel
      • Reserve Stock
      • Cancel Stock
      • Commit Stock
      • Refund Stock
      • Get Current Stock
    • Product Supplier
      • Receive Stock
      • Receive Price
      • Get Stock/Price History
      • Check Batch Status
      • Remove My Products
      • Clean My Products
      • Export Stock/Price
      • List Exports
      • Get Exported Files
    • Global Products
      • Receive Products
      • Get Global Products
      • Remove Global Products
  • Common
    • Dataset
      • Create
      • Update
      • Delete
      • Value Upsert
      • Value Delete
      • List Sources
      • List Values
  • How to
    • Creating a Promotion Template
    • Promotion Transaction Flow
    • Understanding PIM Product Statuses
  1. How to

Creating a Promotion Template

Introduction#

You can access promotion templates from the Promotions -> Promotion Settings -> Templates section. Currently, only authorized comple.io or Retter employees can edit promotion templates in the respective project.
Below, you can follow the step-by-step process for creating a promotion template:

Step 1: Defining the Required Parameters#

To define the parameters that will be used in your promotion template, you need to use the Promotions -> Promotion Settings -> Parameters screen. Parameters will be used as variables within the template and allow for customization of the promotion. Keep in mind that the code and type of defined parameters cannot be changed later. Therefore, make sure you correctly define the required parameters in advance.

Step 2: Template Creation#

By carefully planning your templates and making the most of customization options, you can create impressive promotions. Comple.io's dynamic template structure allows you to easily implement thousands of different promotion scenarios.

Template Name#

You can create meaningful descriptions that express what your promotion is, such as "Buy X Get Y Free" or "Get Z% Discount on Y Product with X Purchase."

Template Type#

ou can choose between two template types: normal and coupon.
If you choose the normal type, templates will operate based on logical comparisons you create with JavaScript code.
If you choose the coupon type, the validity of the coupon will be checked first, and then it will operate based on the logical comparisons you create with your JavaScript code. Additionally, a section for dynamically generating coupons will be added to the screen.

Template Description#

You can write detailed explanations about the promotion.

Parameters#

Promotions -> Promotion Settings -> Parameters You can add the parameters you've defined on your screen to your template from here. These parameters will be used to customize your promotion. Please note that once added, these parameters cannot be removed after being used in a promotion.
When you add a parameter, the TypeScript type definitions at the top of your code for params will be updated to facilitate error-free and comfortable code development.

Context#

promotionId: You can use this promotion ID when calculating the relevant promotion derived from the template. For example, when returning to the calculate method of a previously applied promotion in your calculations, you can send it in a field like excludedPromotion to prevent the relevant promotion from being applied.
userTransactions: This parameter is used to access the user's past transaction data. This allows access to information on how many times the customer has used the relevant promotion.
couponGiftAmount: This parameter is used to obtain the amount assigned to a coupon. If there is an amount assigned to the coupon, it can be retrieved through this parameter.

Gift Amount Calculator#

In this section, there is a method that determines how the gain for the promotion will be calculated. This method can return both string and numerical values. The operation is as follows:
1.
If the method returns zero (0), the user is considered to have gained nothing from this promotion.
2.
If the method returns a numerical value greater than zero as a result of logical comparisons, the gained amount for the relevant promotion will be considered as this value.
3.
If you return a string value, it will be returned in the response within cart.suggestionPromotions[] as an object in the following format.
{
  "id": "promotionId",
  "userMessage": "User message defined in the promotion",
  "suggestion": "If you add one more X product, you will receive a discount of Y TL",
}
4.
If the script returns an object:
If the object contains a suggestion field, this value is added as a "suggestion."
If the object includes a giftAmount value, it can be applied as a discount.
Additionally, the additionalData field in the object can be used to return any required supplementary information.
{
     "suggestionPromotions": [
            {
                "id": "ORNS8M1ROXCXY988",
                "userMessage": "",
                "suggestion": "Get 1 more and have 20% discount!",
                "additionalData": {
                    "addToCart": [
                        1, // productID
                        2,
                        3
                    ]
                }
            }
        ]
}
This structure provides a flexible and comprehensive way to handle various data types, enabling the system to manage both suggestions and discounts effectively.

Buy X and get a discount of Y TL#

An example of a promotion where you get a discount of Y TL when you purchase any one X product:
function calculatePromotion(
    body: { subOrders: Array<{ id: string }> },
    params: { amoutOff: number; buyProductIds: string[] },
    context:{ promotionId: string, userTransactions?: any[], couponGiftAmount?: number },
) {
    // We are checking if there is any product from the "buyProductIds" parameter within the "subOrders."
    return body.subOrders.some((s) => params.buyProductIds.includes(s.id))
        ? params.amoutOff
        : 0;
}

const body = {
    subOrders: [
        {
            id: '1',
        },
        {
            id: '2',
        },
    ]
};

const params = {
    buyProductIds: ["1", "2", "3", "5"], // Apply a discount if any of these products are purchased
    amoutOff: 50, // The total amount eligible for the discount
};

// Result: A discount of 50 TL has been calculated based on the purchase of the X product with the existing parameters and returned.
console.log(calculatePromotion(body, params));
You can test with TypeScript Playground live!

Buy X, get Y for Z TL#

An example of a promotion that returns the total discount amount for the Y product at the price of Z TL for each quantity purchased of the X product:
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));
You can test with TypeScript Playground live!

Gift Item Selector#

In this section, we determine how the discount earned for the promotion will be distributed to the "priceAfterPromotion" field. All you need to do is iterate through the relevant subOrder items for which you want the discount to be distributed, and distribute it in proportion to the weight of the respective gain.

Apply to the products that need to be purchased for the discount and to the products where the discount is applied.#

You can use it only to apply to products related to the discount.

Apply to all products in the cart.#

In this type of promotion, we distribute the discount to all products in proportion to their weights. It's worth noting that this method is often preferred to minimize accounting issues.

Apply only to the serviceFee#

This type of promotion can be used to create scenarios like free shipping promotions.

Calculate Display Price#

"In this section, you can distribute the discount amount to the prices of products in different ways to make them appear more appealing to the end user.
This representation is often used in template models where we want to specify which product is free, similar to 'buy one, get one free' scenarios.
**Note: The Calculate Display Price field is not mandatory. If left empty, the response will default to displaying the product's price information in the displayPrice field."

Detailed Example#

The following example provides a detailed scenario with all the mentioned Gift Amount Calculator, Gift Item Selector, and Calculate Display Price scripts prepared for a comprehensive scenario. Sample bodies and parameters are defined, and detailed comments have been written. You can easily test it in a TypeScript playground by manipulating the body and parameter values.
The provided template is designed to generate promotions in the format of "Get X items of Y for Z with a %T discount." Additionally, the example includes certain values from the body of the calculate method that are integrated into the promotion process.
You can test with TypeScript Playground live!
Modified at 2024-11-26 14:28:48
Previous
List Values
Next
Promotion Transaction Flow
Built with