Quickly Generate Inventory Files in Salesforce Commerce Cloud using Nodejs

Generate Inventory XMLs in Salesforce Commerce Cloud using Node JS

Salesforce Commerce Cloud – known as ‘Demandware’ until the recent acquisition by Salesforce – is used by major global retail brands including Adidas, Burton, Puma, and Lacoste. The basic proposition of the platform is that, by offering ecommerce as a SaaS solution, it frees your business from the demands of managing a technical roadmap – or figuring out how to stay ahead of the curve when it comes to best practice ecommerce features. 

Too often, especially during testing, products are not ‘available’ as there is no inventory. For a quick fix, you can use the following code to generate inventory XMLs to upload in the Business Manager – making it easy to test.

Generating the Salesforce Inventory File

Before you build the inventory, you need a list of products to get started. The following details out the the key requirements:

What you’ll need

You’ll need the following

  1. A CSV of Product Ids
  2. Nodejs installed in your local system
  3. csv-parse (installed via npm install csv-parse)
  4. Access to import/export files in SFCC Business Manager

The code

// fill this
var inventoryId = '';
var inputProductList = ' '; // filename of the CSV of product Ids - make sure it is in the same directory as this file.
var outputXML = 'inventory.xml'; // rename the output XML file
var headerChecker = 0 ;// = 1 if there is a file header
var yourName = ''; //your name for logging


var today = new Date().toISOString().slice(0, 10);

const parse = require('csv-parse');
var fs = require('fs');
var wstream = fs.createWriteStream(outputXML);    
wstream.write('<?xml version="1.0" encoding="UTF-8"?>'+
                +'<inventory xmlns="http://www.demandware.com/xml/impex/inventory/2007-05-31">'+
                    '<inventory-list>'+
                        +'<header list-id="'+inventoryId+'">'+
                            +'<default-instock>true</default-instock>'+
                                +'<description>Inventory List updated : by '+ yourName?yourName:"Script"
                                    +'</description>'+
                                        +'<use-bundle-inventory-only>false</use-bundle-inventory-only>'+
                                            +'<on-order>false</on-order>'+
                                                +'</header><records>');




var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream(inputProductList)
  
});
var counter = 0;

//create a function that starts reading the file line by line... and stores the details in an object.


async function getLineValues(){
    var headerChecker = 0
    var bigArray = []; // this guy contains the line in an array format
    lineReader.on('line', await function (line) { // here we write the object to create the XML file. I don't know why we did that. But you can potentially add more code. We're running linear here so there are no worries.
        //setthevalues:
        line = line.replace('&','&');
        bigArray = CSVtoArray(line);
        var productId = bigArray[0];
        productString += '<record product-id="'+productId+'">'+
                            +'<allocation>99</allocation>'+
                                +'<allocation-timestamp>'+today+'T00:00:03.000Z</allocation-timestamp>'+
                                    +'<perpetual>true</perpetual>'+
                                        +'<preorder-backorder-handling>none</preorder-backorder-handling>'+
                                            +'<ats>99</ats>'+
                                                +'<on-order>0</on-order>'+
                                                    +'<turnover>0</turnover></record>';
        //await wstream.write(productString); 
    })
    .on('close', async function(){
        await wstream.write(productString + ' </records>\n</inventory-list>\n</inventory>');
        wstream.close();       
    
});


}

function CSVtoArray(text) {
    var re_valid = /^\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*(?:,\s*(?:'[^'\\]*(?:\\[\S\s][^'\\]*)*'|"[^"\\]*(?:\\[\S\s][^"\\]*)*"|[^,'"\s\\]*(?:\s+[^,'"\s\\]+)*)\s*)*$/;
    var re_value = /(?!\s*$)\s*(?:'([^'\\]*(?:\\[\S\s][^'\\]*)*)'|"([^"\\]*(?:\\[\S\s][^"\\]*)*)"|([^,'"\s\\]*(?:\s+[^,'"\s\\]+)*))\s*(?:,|$)/g;
    // Return NULL if input string is not well formed CSV string.
    if (!re_valid.test(text)) return null;
    var a = [];                     // Initialize array to receive values.
    text.replace(re_value, // "Walk" the string using replace with callback.
        function(m0, m1, m2, m3) {
            // Remove backslash from \' in single quoted values.
            if      (m1 !== undefined) a.push(m1.replace(/\\'/g, "'"));
            // Remove backslash from \" in double quoted values.
            else if (m2 !== undefined) a.push(m2.replace(/\\"/g, '"'));
            else if (m3 !== undefined) a.push(m3);
            return ''; // Return empty string.
        });
    // Handle special case of empty last value.
    if (/,\s*$/.test(text)) a.push('');
    return a;
};


getLineValues();

Getting the file

The following steps should simplify affairs. This is aimed at a beginner level:

  1. Install nodejs if you haven’t already (if you’re using Mac, please use Homebrew to install nodejs – I find it easier to manage using Brew).
  2. Create a new directory in Terminal/Powershell.
    mkdir inventory
    cd inventory
  3. Hopefully, you have a CSV that contains just the product-id. Remove the header if you have one.
  4. Type ‘npm install csv-parse’ to install the csv-parse library
  5. Wait for the installation to complete
  6. Create a new file & open it:
    touch inventory.js
    edit inventory.js
  7. Fill up the first section.
  8. Save the file
  9. Run the script:
    node inventory.js
  10. Verify the output

After verification, you can open SFCC Business Manager and upload the file through the Import/Export File option under Product & Catalog Section in the Merchant Menu. Import the inventory. Check for errors.

You can verify that the inventories are working by viewing the product.


That’s all! If you are facing issues, please feel free to reach out to me with your questions. Comment here or DM me.


Thank you for reading. I’ll be making more SFCC oriented quick-wins and training articles here, so please subscribe!

0
Get your weekly dose of Marginal Gains!

Subscribe to get a weekly mail that'll help you make marginal gains in your Product Management journey!

Leave a Reply

Your email address will not be published. Required fields are marked *