website logo
Product FeedCommunity Forum
API Docs
Template JS
Headless SDK
Navigate through spaces
API Docs
Template JS
Headless SDK
⌘K
Introduction
Getting Started
Quickstart : Smart Search
Quickstart : Smart Category Merchandising
Quickstart : Smart Recommendations
Apps/Plug-ins
Guide
Structure
Configuration
JS Library
Versioning
Template Reference
Build UI
Custom Overrides
Recommendations Webhooks
Styling CSS
Analytics/Tracking
How To
Add Filters To URL
Add Pagination To URL
Add-To-Cart Function
Customer Groups
Infinite Scroll Results
Magento B2B MSI
Ratings / Reviews
SortBy Options
Docs powered by archbee 
21min

Magento B2B MSI



The current version of Klevu’s Magento extension does not natively support indexing of Magento's Multi Source Inventory (Inventory Management) values. The values must be provided into the Klevu index so that they may be used for constraining the results to the desired source availability and/or indicating inventory.

Two parameters are required at the product level during indexing:

  1. One to identify the item is sold at the selected location
  2. One to identify the item is in stock at the selected location

On the website front-end, a filter is applied “behind the scenes” to the outgoing search query to constrain results to the visitors selected source/store.

If you are looking for MSI Salable Availability (true/false) only, please review our sub module add-on to see if it useful for your scenario. https://github.com/klevu/msi



The solution below will explain:

1] Options to provide the availability data and stock status at the product level to the Klevu Index:

  • Extend the Klevu Search Module
  • Klevu Feed XML
  • Klevu Indexing API

2] Options to modify the outgoing search query to filter by the selected source and/or stock status:

  • Klevu Search API
  • Template JS V2 override
  • Template JS V1 variable

If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact Customer Support for guidance specific to your version.



The option selected for Indexing and Query will apply globally. It is recommended to NOT mix Indexing methods.

Note: the methods for obtaining the availability data will be the responsibility of your development team.

Once the availability values have been indexed, the outgoing search queries to Klevu can use the values for filtering based on source and/or stock availability. 

Note: the name and value pairs used in this document are for examples only. The actual values can be whatever best fits the implementation and business requirements so long as they are consistent.

For Example:

Example variable naming
Example variable naming






Indexing

Options to provide the availability data and stock status at the product level to the Klevu Index:

  • Extend the Klevu Search Module
  • Klevu Feed XML
  • Klevu Indexing API



Option 1: Extend the Klevu Search Module

Extend Klevu's Magento module to include the availability datapoints at the product level during catalog indexing.

The Klevu module contains a function designed for adding additional datapoints. This function can be extended as preference and used for additional parameters added at the product level during indexing.

vendor/klevu/module-productsearch/Model/Product/LoadAttribute.php -> processProductAfter()

PHP
|
  /**
     * Process product data if want to add any extra information from third party module
     * @param $product
     * @param $parent
     * @param $item
     * @return $this|mixed
   */

    public function processProductAfter(&$product ,&$parent,&$item){
       return $this;
    }


Source reference : Klevu productsearch on github 



Example extended class and logic:

Because there are many ways to work within the Magento framework, the actual implementation as well as methods and applied logic for the availability data will be the responsibility of your development team.

It is strongly recommended to properly extend the Klevu extension for this purpose to avoid potential conflicts during future updates to the system.

1] Extend the LoadAttribute class as preference.

XML
|
<preference for="Klevu\Search\Model\Product\LoadAttribute"
            type="Klevu\Override\Model\Product\LoadAttributeCustom"/>


2] Override the processProductAfter function within the LoadAttribute class.

This example adds source_availability and source_instock as facets to the Klevu module's Indexing API call to Klevu. The product is sold at Location1 and Location2 (comma separated Array), but is only in stock at Location1.

PHP
|
class LoadAttributeCustom extends \Klevu\Search\Model\Product\LoadAttribute
{

     public function processProductAfter(&$product ,&$parent,&$item)
     {

         if (GET SOURCE DATA) {
     
              $product["other"]["source_availability"] = ["Location1,Location2"];
              
              if (SOURCE STOCK LOGIC HERE) {
                  $product["other"]["source_instock"] = "Location1";
              }
         
              return $this;
         }
    }

}


API reference : Data Indexing



Option 2: Klevu Feed XML

You may disengage the Klevu module's built-in sync and provide an external XML feed file with the full catalog data, including the additional Availability datapoints.

Please reference the Knowledge Base article for more information on using XML for data indexing.

The source availability datapoints can be entered using the <attribute> node.

In this example the product is sold at Location1 and Location2, but is only in stock at Location1.  

XML
|
 . . .
 <attributes>
  . . .
  <attribute>
      <id>source_availability</id>
      <name>Source Availability</name>
      <is_facet>true</is_facet>
      <values>
          <value>Location1</value>
          <value>Location2</value>
      </values>
  </attribute>
  <attribute>
      <id>source_instock</id>
      <name>Source InStock</name>
      <is_facet>true</is_facet>
      <values>
          <value>Location1</value>
      </values>
  </attribute>
  . . .
</attributes>
. . .


Note: <is_facet> is set to true to allow filtering on the attribute. 

Source References :  Klevu Feed Format Guide and Klevu Feed Example XML



Option 3: Klevu Indexing API

You may disengage the Klevu module's built-in sync and use Klevu’s Data Indexing directly for indexing the full catalog data, including the additional Availability datapoints.

The source availability datapoints can be sent using the other key:value pair (as facets)

In this example the product is sold at Location1 and Location2, but is only in stock at Location1.  

XML
|
<?xml version="1.0" encoding="UTF-8" ?>
<request>
<sessionId>Your-Session-ID</sessionId>
  <records>
    <record>
      <pairs>
        <pair>
         <key>other</key>
         <value>source_availability:source_availability:Location1,Location2;source_instock,source_instock,Location1</value>
        </pair>
    . . .
    


API reference : Data Indexing



Querying

Options to modify the outgoing search query to filter by the selected source and/or stock status:

  • Klevu Search API
  • Template JS V2 override
  • Template JS V1 (Legacy)

If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact Customer Support for guidance specific to your version.



Option 1: Klevu Search API

Using the API parameter customANDQuery, a constraint can be applied for the query to those items that correspond to the selected source_availability value.

Example API request JSON using customANDQuery constraint

This example adds source_availability and source_instock as filters to the Template JS API call to Klevu. The web visitor has selected to see items sold at Location1 and only in stock at Location1.

JSON
|
  "recordQueries": [
    {
      "settings": {
         "id": "productSearch",
        "customANDQuery": "(source_availability:\"Location1\") AND source_instock:\"Location1\")",
         . . .
    }
  ]


Source Reference : 



Option 2: Template JS V2 Override

To apply the Availability constraint within the context of the Klevu Template JS UI the outgoing search request needs to be intercepted and modified.

See : Custom Overrides for details on preparing for Klevu JS overriding

You may also find Klevus Example Customization Module on giHub useful for this scenario (and more).



Example override using customANDQuery constraint

This example adds source_availability and source_instock as constraints to the Template JS API call to Klevu. The web visitor has selected to see items sold at Location1 and only in stock at Location1.

The result set will only include items that meet these requirements.

JS
|
klevu.setObjectPath(
    data,
    "localOverrides.query.productList.settings.customANDQuery",
    "(source_availability:\"Location1\") AND (source_instock:\"Location1\")"
);


Note: The above example applies the constraint to productList query only. For a complete Javascript example of applying this to all query, see the Complete Template JS Example below.



Complete Template JS Example

This example uses a common function to apply the availability constraint via customANDQuery override for all queries on Quicksearch, Search Landing, and Category pages.

JavaScript
|
<script type="text/javascript">

// Defer initialization (powerUp) of the Klevu components
    klevu({
        powerUp: {
            quick: false,
            landing: false,
            catnav: false
        }
    });

// OVERRIDE : QUICKSEARCH

    // Define a new custom event, which will fire after Quicksearch has initialised
    klevu.coreEvent.build({
        name: "myQuickSearchOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigQuick.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myQuickSearchOverride", {
        name: "attachToMyQuickSearchOverridee",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            klevu.search.quick.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyQuickQuery",
                fire: function (data, scope) {
                    // REFERENCE COMMON FUNCTION HERE
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                 }
            });

            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    quick: true
                }
            });
        }
    });


// OVERRIDE : LANDING PAGE

    // Define a new custom event, which will fire after SRLP has initialised
    klevu.coreEvent.build({
        name: "myLandingPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myLandingPageOverride", {
        name: "attachToMyLandingPageOverride",
        fire: function () {
            // Fire the custom javascript action or override an API parameter

            klevu.search.landing.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyLandingQuery",
                fire: function (data, scope) {
                    // REFERENCE COMMON FUNCTION HERE
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                 }
            });

            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    landing: true
                }
            });
        }
    });


// OVERRIDE : CATEGORY PAGE

    // Define a new custom event, which will fire after Category page has initialised
    klevu.coreEvent.build({
        name: "myCategoryPageOverride",
        fire: function () {
            if (klevu.getGlobalSetting("flags.setRemoteConfigCatnav.build", false)) {
                return true;
            }
            return false;
        },
        maxCount: 150,
        delay: 100
    });

    // Listen for the new custom event
    klevu.coreEvent.attach("myCategoryPageOverride", {
        name: "attachToMyCategoryPageOverride",
        fire: function () {
            // Fire the custom javascript action or override an API parameter
 
            klevu.search.catnav.getScope().chains.request.control.addAfter("initRequest", {
                name: "modifyCatnavQuery",
                fire: function (data, scope) {
                    // REFERENCE COMMON FUNCTION HERE
                    klevu.search.modules.addMyOverrideToQuery(data, scope);
                }
            });

            // Activate the initialization (powerUp)
            klevu({
                powerUp: {
                    catnav: true
                }
            });
        }
    });

// COMMON OVERRIDE FUNCTION

    (function (klevu) {
    klevu.extend(true, klevu.search.modules, {
        addMyOverrideToQuery: function (data, scope) {
            klevu.each(data.request.current.recordQueries,function(key, query){ 
                
                // OVERRIDE API PARAMETER HERE
                // SET query contraints by availability location/stock
                klevu.setObjectPath(
                  data,
                  "localOverrides.query." + query.id + ".settings.customANDQuery",
                  "(source_availability:\"Location1\") AND (source_instock:\"Location1\")"
                );
 
            });
        }
    });
})(klevu);
</script>




Option 3: Template JS V1 (Legacy)

Klevus legacy template provides a basic means to apply preset filters via a JavaScript variable.

This example adds source_availability and source_instock as filters to the Template JS API call to Klevu. The web visitor has selected to see items sold at Location1 and only in stock at Location1.

JS
|
var klevu_userFilterResults = "source_availability:Location1;;source_instock:Location1";




Updated 03 Mar 2023
Did this page help you?
Yes
No
UP NEXT
Ratings / Reviews
Docs powered by archbee 
TABLE OF CONTENTS
Indexing
Option 1: Extend the Klevu Search Module
Option 2: Klevu Feed XML
Option 3: Klevu Indexing API
Querying
Option 1: Klevu Search API
Option 2: Template JS V2 Override
Option 3: Template JS V1 (Legacy)