---
title: Magento B2B MSI
slug: template-js/magento-b2b-msi
docTags: 
createdAt: 2022-09-12T14:45:49.000Z
---



The current version of Klevu’s Magento extension does not natively support indexing of Magento's Multi Source Inventory ([Inventory Management](https://developer.adobe.com/commerce/webapi/rest/inventory/)) 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.

:::hint{type="info"}
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](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

:::hint{type="info"}
If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact [Customer Support ](https://help.klevu.com/support/tickets/new)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:

::Image[]{src="https://api.archbee.com/api/optimize/816_4eGYZQxALlijMlcBN/MZRMaGvGuBa94o6iAAos5_image.png" size="82" width="1009" height="465" caption="Example variable naming" position="center" showCaption="true"}





## 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](https://github.com/klevu/productsearch/blob/379fea472dbf1fa4eb15c3bcbf943fcb953fb89b/Model/Product/LoadAttribute.php#L295). 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 : &#x20;**[Klevu productsearch on github](https://github.com/klevu/productsearch/blob/379fea472dbf1fa4eb15c3bcbf943fcb953fb89b/Model/Product/LoadAttribute.php#L295)&#x20;

****

**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.

:::hint{type="warning"}
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&#x20;**(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 :&#x20;**[Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db)&#x20;

****

### Option 2: Klevu Feed XML

You may disengage the Klevu module's built-in sync and provide an external [XML feed](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) file with the full catalog data, including the additional Availability datapoints.

Please reference the [Knowledge Base article](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) 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:&#x20;**\<is\_facet> is set to *true* to allow filtering on the attribute. 

**Source References :**  [Klevu Feed Format Guide](https://help.klevu.com/support/solutions/articles/5000871297-feed-format) and [Klevu Feed Example XML](https://github.com/klevu/feed/blob/dce928eb1c97115cc0bfbba7500d5241751d5ce4/sample.xml#L347)



### Option 3: Klevu Indexing API

You may disengage the Klevu module's built-in sync and use Klevu’s [Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db) 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 :&#x20;**[Data Indexing](docId:5yQa6EtAyYYQzWQHfx_db)&#x20;



## 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)

:::hint{type="info"}
If you are using the “Preserve your Magento layout” option of the Klevu Magento Module, please contact [Customer Support](https://help.klevu.com/support/tickets/new) 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&#x20;*****customANDQuery*****&#x20;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 :**&#x20;



### 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](docId:_bc3GcThleEaToYujDtuE) for details on preparing for Klevu JS overriding

:::hint{type="success"}
You may also find Klevus [Example Customization Module](https://github.com/klevu/themev2-customisation-module/tree/master/Acme) on giHub useful for this scenario (and more).
:::



**Example override using&#x20;*****customANDQuery*****&#x20;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.

```javascript
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.

:::CodeblockTabs
JavaScript

```typescript
<script type="text/javascript">
klevu.modifyRequest("landing,catnav", function(data, scope){
    
  // loop through all the pending queries
  klevu.each(data.request.current.recordQueries,function(key, query){ 

      // SET query contraints by availability location/stock
      klevu.setObjectPath(data,
         "localOverrides.query." + query.id + ".settings.customANDQuery",
         "(source_availability:\"Location1\") AND (source_instock:\"Location1\")"
       );

  });

});
</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**.

```javascript
var klevu_userFilterResults = "source_availability:Location1;;source_instock:Location1";
```

