Inventory update in WooCommerce.

Jira Code: MISC-147

Sync NetSuite inventory count to Woocommerce

We are using the Woocommerce API to fetch the products from Woocommerce. Here we have used a test item ‘ PTWIDGET ’ to test the update process. From the fetched products we perform the updation for the test item given. The ITEMID available in the NetSuite is  Map to Woocommerce product SKU.

We are using the NetSuite ITEMID and Woocommerce product SKU to match the items in NetSuite to update the product count in Woocommerce. If an item in NetSuite is present in the item search, for test item SKU, it checks for the quantity on hand. If the quantity in NetSuite >0, updates the available quantity to Woocommerce and displays status: In Stock. In the else part updates the available quantity as Zero to Woocommerce and displays status: Out of Stock.

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/**
	 * Script Description
	 * To search PTWIDGET item of woocommerce in netsuite and find the item and 
	   fetch id to retrieve a specific product.
	 **/
	/*******************************************************************************
	 * ProTec
	 * **************************************************************************
	 * 
	 * Date: 09-07-2018
	 * 
	 * Author: Jobin & Jismi IT Services LLP
	 * 
	 * 
	 * REVISION HISTORY 
	 * 
	 * Revision 1 $ 17-07-2018 rijoy_paul : Created
	 * 
	 *****************************************************************************
	 **/
define(['N/file', 'N/http', 'N/https', 'N/record', 'N/runtime', 'N/search'],
/**
 * @param {file} file
 * @param {http} http
 * @param {https} https
 * @param {record} record
 * @param {runtime} runtime
 * @param {search} search
 */
function(file, http, https, record, runtime, search) {
   
    /**
     * Definition of the Suitelet script trigger point.
     *
     * @param {Object} context
     * @param {ServerRequest} context.request - Encapsulation of the incoming request
     * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
     * @Since 2015.2
     */
    function onRequest(context) {
     try{
			/*To fetch all product using Woocommerce API*/
			var response=https.get({
				url:'https://www.protecstyle.com/wp-json/wc/v2/products?per_page=100',
				headers:{
					'authorization':'Basic Y2tfMDhlYzRiZDI3NjcxY2JlNDc2OGUzZjFjMWI0MTBhNGJkNTJmZTY1Yjpjc18wMTI0Zjg4YTQ0NjI1YzU1YmY4YmU1YjI2ZmQ1MWNkNmRiMzljNTgz',
				 }
			  });
			var W_items=[];
			var content = JSON.parse(response.body);
			var W_skuIds=[];
			for(var i=0;i<content.length;i++)
			{  if(content[i].sku=="PTWIDGET")
			   {
				    W_skuIds.push(content[i].sku);
				    W_items.push({
					item_id:content[i].id,
					item_sku:content[i].sku,
					item_StockQuantity: content[i].stock_quantity,
					item_Stock_Status: content[i].in_stock,
					 /*W_skuIds.push(content[i].sku);
				       W_stockQ.push(content[i].stock_quantity);
				       W_inStock.push(content[i].in_stock);*/   
				   });		
			   }
			}
				
				  /*W_skuIds.push(content[i].sku);
				    W_stockQ.push(content[i].stock_quantity);
				    W_inStock.push(content[i].in_stock);*/
			   
			
			log.debug({
				title:'W_items',
				details:W_items
			});
			/*log.debug({
				title:'W_stockQ',
				details:W_stockQ
			});*/
			
			/*saved search to fetch all items from Netsuite based on 
			  itemid,active & quantity available*/
			var itemSearch=search.create({
				type:search.Type.ITEM,
				columns:
					   [
					      search.createColumn({
					         name: 'locationquantityonhand',
					         summary: 'SUM',
					         label: 'Location On Hand'
					      }),
					      search.createColumn({
					         name: 'itemid',
					         summary: 'GROUP',
					         sort: search.Sort.ASC,
					         label: 'Name'
					      })
					   ],
				 filters: [{
			        name: 'isinactive',
			        operator: 'is',
			        values: ['F']
				}]

			});
			var searchResultCount = itemSearch.runPaged().count;
			log.debug("Result Count",searchResultCount);

			/*saved search to fetch results more than 1000 item records*/
			var start = 0;
			var end = 1000;
			var NW_commonItems = [];
			var count=0;
			var result;
			var singleresult;
			var response1=[];
			
			for (var i = 0; i < Math.ceil(searchResultCount / 1000); i++) 
			{ 
				result = itemSearch.run().getRange({
					start: start,
					end: end
				});

				for (var j = 0; j < result.length; j++) {
					singleresult = result[j];
					/*Netsuite itemid of items*/
					var N_skuId=singleresult.getValue({
						name:'itemid',
						summary:'GROUP'
					  });
					/*Netsuite item quantity */
					  var qty_Available=singleresult.getValue({
						name:'locationquantityonhand',
						summary:'SUM'
					  });
					/*To find all items  matches in Netsuite fetched from Woocommerce */ 
					var a=W_skuIds.indexOf(N_skuId) ;
					if(a>-1)
					{   count++;
					   NW_commonItems.push({
						WS_id:content[a].id,
						WS_sku:content[a].sku,
						WS_StockQuantity: content[a].stock_quantity,
						WS_Stock_Status: content[a].in_stock,
						NS_sku:N_skuId,
						NS_stockQ:qty_Available
					    });
					   /*To update for Quantity check >0 for items matched */
					    if(qty_Available>0)
					     {
					         response1.push(https.put({
						     url:'https://www.protecstyle.com/wp-json/wc/v2/products/'+content[a].id,
						     headers:{
							      "authorization": "Basic Y2tfMDhlYzRiZDI3NjcxY2JlNDc2OGUzZjFjMWI0MTBhNGJkNTJmZTY1Yjpjc18wMTI0Zjg4YTQ0NjI1YzU1YmY4YmU1YjI2ZmQ1MWNkNmRiMzljNTgz",
							      "Content-Type": "application/json",
						     },
						     body:JSON.stringify({
							       "stock_quantity":qty_Available,
							       "in_stock": "true"
							  
						      })				
					        })); 
					      }
					    else
					      {
					    	 
					    	     response1.push(https.put({
							     url:'https://www.protecstyle.com/wp-json/wc/v2/products/'+content[a].id,
							     headers:{
								      "authorization": "Basic Y2tfMDhlYzRiZDI3NjcxY2JlNDc2OGUzZjFjMWI0MTBhNGJkNTJmZTY1Yjpjc18wMTI0Zjg4YTQ0NjI1YzU1YmY4YmU1YjI2ZmQ1MWNkNmRiMzljNTgz",
								      "Content-Type": "application/json",
							     },
							     body:JSON.stringify({
								       "stock_quantity":"0",
								       "in_stock": "false"
								  
							      })				
						        })); 
					      }
					    	
					    }
 
				}	


				start = end;
				end = end + 1000;

			}
			
			log.debug({
				title:'COUNT',
				details:count
			});		  
			log.debug({
				title:'NW_commonItems',
				details:NW_commonItems
			});	
			log.debug({
				title:'response1',
				details:response1
			});
			
			context.response.write(JSON.stringify( response1));
     }
		catch(e)
		{
			log.debug({
    	    	title:'err@Get',
    	    	details:e
    	      }); 
			context.response.write('Failure');
		}

    }

    return {
        onRequest: onRequest
    };
    
});

Leave a comment

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