Jira Code: PROT-158
Integration should be performed so as to update inventory between Woocommerce and NetSuite ERP platform. Inventory management is an easy, accurate, and profitable method to manage inventory records. Through inventory management, any transaction for items that take place will automatically update the corresponding quantity details. The advantage is that they do not need to re-enter the amounts for those items.
A scheduled script runs within an interval of time and checks the inventory details of items in NetSuite and update it in Woocommerce. Another suitelet form shows the changes made in NetSuite and Woocommerce for the ease of the client to understand the changes and updates.
PROT-158 JJ SS Woocommerce iloveblvd Scheduled Script
/**
* @NApiVersion 2.x
* @NScriptType ScheduledScript
* @NModuleScope SameAccount
*/
/**
* Script Description
* This script will periodically update inventory in WooCoomerce with values in NetSuite
* ie, Inventory Sync
*
* Date Created : 19-December-2018
*/
/*******************************************************************************
* * ProTec | Boulevard | PROT-158 | WooCommerce Inventory Update *
* **************************************************************************
*
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 19-December-2018
*
* REVISION HISTORY
*
*
******************************************************************************/
/**
* SCRIPT ID : customscript_prot158_jj_ss_woocommerce_
*
* DEPLOYMENT ID : customdeploy_prot158_jj_ss_woocommerce_
*
*/
/*
* WooCommerce API Reference : http://woocommerce.github.io/woocommerce-rest-api-docs/
*/
define(['N/https', 'N/search', 'N/runtime', 'N/task', 'N/url', 'N/format', 'N/log', 'N/email'],
function(https, search, runtime, task, url, format, log, email) {
//To check whether a value exists in parameter
function checkForParameter(parameter, parameterName) {
if (parameter != "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== 'false' && parameter != " ")
return true;
else {
if (parameterName)
log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
return false;
}
}
//To assign a default value if the it is empty
function assignDefaultValue(value, defaultValue) {
if (checkForParameter(value))
return value;
else
return defaultValue;
}
//WooCommerce REST API Calls for Product Management
var wooCommerceAPIObj = {
listProducts: function(domain_url, auth, pageIndex) {
var request_url = url.format({
domain: domain_url + '/wp-json/wc/v2/products',
params: {
per_page: '100',
page: assignDefaultValue(pageIndex, 1),
status: 'publish'
}
});
log.debug('listProducts request_url', request_url);
var response = https.get({
url: request_url,
headers: { authorization: auth }
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
},
fetchProduct: function(domain_url, auth, id) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/products/' + id,
headers: { authorization: auth }
});
log.debug('fetchProduct url', domain_url + '/wp-json/wc/v2/products/' + id);
return JSON.parse(response.body);
},
updateProduct: function(domain_url, auth, id, bodyObj, parentId) {
log.debug('bodyObj ', bodyObj);
log.debug('parentId ', parentId);
var response = https.put({
url: checkForParameter(parentId) ? (domain_url + '/wp-json/wc/v2/products/' + parentId + '/variations/' + id) : (domain_url + '/wp-json/wc/v2/products/' + id),
headers: {
'Authorization': auth,
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyObj)
});
log.debug('updateProduct url', domain_url + '/wp-json/wc/v2/products/' + id);
log.debug('response.body', response.body)
return response.body;
}
};
for (var key in wooCommerceAPIObj) {
if (typeof wooCommerceAPIObj[key] === 'function') {
wooCommerceAPIObj[key] = trycatch(wooCommerceAPIObj[key], 'wooCommerceAPIObj.' + key);
}
}
//main or root object for this entire scheduled script
var main = {
searchForInventoryItem: function() {
var responseObj = {};
var inventoryitemSearchObj = search.create({
type: "inventoryitem",
filters: [
["isinactive", "is", "F"],
"AND",
["type", "anyof", "InvtPart"],
"AND",
["caption", "isnotempty", ""]
],
columns: [
search.createColumn({
name: "internalid",
summary: "GROUP",
label: "Internal ID"
}),
search.createColumn({
name: "itemid",
summary: "MAX",
label: "Name"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityonhand},0)",
label: "Formula (Numeric)"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityavailable},0)",
label: "Formula (Numeric)"
}),
search.createColumn({
name: "storedisplayname",
summary: "GROUP",
sort: search.Sort.ASC,
label: "Store Display Name"
})
]
});
var searchResultCount = inventoryitemSearchObj.runPaged().count;
log.debug("inventoryitemSearchObj result count", searchResultCount);
inventoryitemSearchObj.run().each(function(result) {
// .run().each has a limit of 4,000 results
responseObj[result.getValue({
name: "storedisplayname",
summary: "GROUP",
label: "Store Display Name"
})] = {
internalid: result.getValue({
name: "internalid",
summary: "GROUP",
label: "Internal ID"
}),
itemid: result.getValue({
name: "itemid",
summary: "MAX",
label: "Name"
}),
sku: result.getValue({
name: "storedisplayname",
summary: "GROUP",
label: "Store Display Name"
}),
quantityonhand: result.getValue({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityonhand},0)",
label: "Formula (Numeric)"
}),
quantityavailable: result.getValue({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityavailable},0)",
label: "Formula (Numeric)"
})
};
return true;
});
log.debug('searchForInventoryItem responseObj', responseObj);
return responseObj;
},
execute: function(scriptContext) {
var currentDate = new Date();
log.debug('EXECUTION STARTS', 'EXECUTION BEGINS AT ' + (currentDate.toUTCString()));
var itemSearchObj = main.searchForInventoryItem();
//WooCommerce Authorisation Details
var WOOCOMMERCE_AUTH = [{
Website_URL: 'https://iloveblvd.com',
API_Name: 'JJ NS-WC Inventory Sync',
API_Authorization: 'Basic Y2tfODY5ZWYyZTllNWYzYmZjNTM0NGE4ZjlmNjkzNGJmZWMzNjk2N2UzNjpjc18zZTMzZTFhODk0MjgxMTk2YzMxYTIxY2ZkOGUzNTE1MzNlMWE0Mzky',
Consumer_Key: 'ck_869ef2e9e5f3bfc5344a8f9f6934bfec36967e36',
Consumer_Secret: 'cs_3e33e1a894281196c31a21cfd8e351533e1a4392'
}];
WOOCOMMERCE_AUTH.forEach(function(api, api_index) {
var listProducts, wc_url, wc_auth, pageLimit,
pageIndex = 1,
sendAnotherRequest = false,
productArray = [],
skuArray = [],
mapObj = {};
log.debug('PROCCESSING FOR ', api.Website_URL);
// log.debug('api ', api);
wc_url = api.Website_URL;
wc_auth = api.API_Authorization;
var itemSearchObj = main.searchForInventoryItem();
do {
listProducts = wooCommerceAPIObj.listProducts(wc_url, wc_auth, pageIndex);
//productArray = productArray.concat(listProducts.body);
productArray = listProducts.body;
log.debug('productArray.length', productArray.length);
productArray.forEach(function(eachProduct) {
if (checkForParameter(eachProduct.variations))
if (eachProduct.variations.length) {
eachProduct.variations.forEach(function(eachVariation) {
productArray.push(wooCommerceAPIObj.fetchProduct(wc_url, wc_auth, eachVariation))
});
}
});
log.debug('NEW productArray.length', productArray.length);
pageLimit = parseInt(listProducts.header['X-WP-TotalPages']);
mapObj = undefined;
mapObj = {};
productArray.forEach(function(eachProduct) {
if (eachProduct.sku && itemSearchObj[eachProduct.sku]) {
mapObj[eachProduct.sku] = {
WooComerce: {
id: eachProduct.id,
sku: eachProduct.sku,
stock_quantity: eachProduct.stock_quantity,
in_stock: eachProduct.in_stock,
manage_stock: eachProduct.manage_stock,
parent_id: checkForParameter(eachProduct.parent_id) ? eachProduct.parent_id : false
//variations: eachProduct.variations //*****//
},
NetSuite: itemSearchObj[eachProduct.sku]
};
log.debug('eachProduct.sku', eachProduct.sku);
log.debug('itemSearchObj[eachProduct.sku]', itemSearchObj[eachProduct.sku]);
}
});
log.debug('Object.keys(mapObj).length ', Object.keys(mapObj).length);
main.processBatch(mapObj, wc_url, wc_auth);
if (pageIndex < pageLimit) {
pageIndex++;
sendAnotherRequest = true;
} else
sendAnotherRequest = false;
if (main.isReschedule())
return true;
} while (sendAnotherRequest);
});
currentDate = new Date();
log.debug('FINAL remainingUsage', main.remainingUsage());
log.debug('EXECUTION ENDS', 'EXECUTION ENDS AT ' + (currentDate.toUTCString()));
},
processBatch: function(mappedObj, wc_url, wc_auth) {
log.debug('mappedObj ', mappedObj);
log.debug('Object.keys(mappedObj).length ', Object.keys(mappedObj).length);
if (checkForParameter(mappedObj)) {
for (var key in mappedObj) {
//if (checkForParameter(mappedObj[key].WooComerce.variations)) { //*****//
//var fetchProduct = //*****//
//} //*****//
//else { //*****//
if (checkForParameter(mappedObj[key].NetSuite)) {
log.debug('mappedObj[key] ', mappedObj[key]);
if (main.toProcess(mappedObj[key]))
wooCommerceAPIObj.updateProduct(wc_url, wc_auth, mappedObj[key].WooComerce.id, {
'manage_stock': true,
'stock_quantity': parseInt(mappedObj[key].NetSuite.quantityavailable),
'in_stock': parseInt(mappedObj[key].NetSuite.quantityavailable) ? true : false
}, mappedObj[key].WooComerce.parent_id);
if (main.isReschedule())
return true;
//} //*****//
}
}
}
},
toProcess: function(singleMappedObj) {
if (singleMappedObj.WooComerce.stock_quantity != singleMappedObj.NetSuite.quantityavailable)
return true;
else if (singleMappedObj.NetSuite.quantityavailable > 0 && !checkForParameter(singleMappedObj.WooComerce.in_stock))
return true;
else
return false;
},
remainingUsage: function() {
//var scriptObj = runtime.getCurrentScript();
var remainingTime = runtime.getCurrentScript().getRemainingUsage();
return remainingTime;
},
rescheduleScript: function() {
var currentDate = new Date();
log.debug('EXECUTION RESCHEDULES', 'EXECUTION RESCHEDULES AT ' + (currentDate.toUTCString()));
var remainingTime = runtime.getCurrentScript().getRemainingUsage();
log.debug("Remaining governance units", remainingTime);
var rescheduleTask = task.create({
taskType: task.TaskType.SCHEDULED_SCRIPT,
scriptId: "customscript_prot158_jj_ss_woocommerce_",
deploymentId: "customdeploy_prot158_jj_ss_woocommerce_",
params: {}
});
var scriptTaskId = rescheduleTask.submit();
log.debug("reschedule scriptTaskId ", scriptTaskId);
return true;
},
isReschedule: function() {
if (parseInt(main.remainingUsage()) < 500)
return main.rescheduleScript();
else
return false;
}
};
for (var key in main) {
if (typeof main[key] === 'function') {
main[key] = trycatch(main[key], 'main.' + key);
}
}
function trycatch(myfunction, key) {
function logDetails(error) {
log.debug("Error in function " + key, JSON.stringify(error));
log.error("Error in function " + key, JSON.stringify(error));
return false;
}
return function() {
try {
return myfunction.apply(this, arguments);
} catch (error) {
logDetails(error);
return false;
}
};
}
return main; //main <--- function root
});
/*******************************************************************************
* return error
*
* @param e
* @returns
*
*/
function getError(e) {
var stErrMsg = '';
if (e.getDetails != undefined) {
stErrMsg = '_' + e.getCode() + '<br>' + e.getDetails() + '<br>' +
e.getStackTrace();
} else {
stErrMsg = '_' + e.toString();
}
return stErrMsg;
}
//Base64 Encode and Decode
var Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function(e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t + this._keyStr.charAt(s) +
this._keyStr.charAt(o) +
this._keyStr.charAt(u) +
this._keyStr.charAt(a)
}
return t
},
decode: function(e) {
var t = "";
var n, r, i;
var s, o, u, a;
var f = 0;
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u != 64) {
t = t + String.fromCharCode(r)
}
if (a != 64) {
t = t + String.fromCharCode(i)
}
}
t = Base64._utf8_decode(t);
return t
},
_utf8_encode: function(e) {
e = e.replace(/rn/g, "n");
var t = "";
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t += String.fromCharCode(r >> 6 | 192);
t += String.fromCharCode(r & 63 | 128)
} else {
t += String.fromCharCode(r >> 12 | 224);
t += String.fromCharCode(r >> 6 & 63 | 128);
t += String.fromCharCode(r & 63 | 128)
}
}
return t
},
_utf8_decode: function(e) {
var t = "";
var n = 0;
var r = c1 = c2 = 0;
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode((r & 31) << 6 | c2 &
63);
n += 2
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode((r & 15) << 12 |
(c2 & 63) << 6 | c3 & 63);
n += 3
}
}
return t
}
};
PROT-158 JJ SS Woocommerce iloveblvd Suitelet
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
* @NModuleScope SameAccount
*/
/*******************************************************************************
* * ProTec | Boulevard | PROT-129 | WooCommerce Inventory Update *
* **************************************************************************
*
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 28-September-2018
*
* REVISION HISTORY
*
*
******************************************************************************/
/**
* SCRIPT ID : customscript_prot129_jj_sl_wc_form
*
* DEPLOYMENT ID : customdeploy_prot129_jj_sl_wc_form
*
*/
/*
* WooCommerce API Reference : http://woocommerce.github.io/woocommerce-rest-api-docs/
*/
define(['N/https', 'N/record', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/url', 'N/log'],
function(https, record, runtime, search, serverWidget, url, log) {
//To check whether a value exists in parameter
function checkForParameter(parameter, parameterName) {
if (parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== "false" && parameter != "" && parameter != " ") {
return true;
} else {
if (parameterName)
log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
return false;
}
}
//To assign a default value if the it is empty
function assignDefaultValue(value, defaultValue) {
if (checkForParameter(value))
return value;
else
return defaultValue;
}
//To reject predefined set of values
function rejectThisValues(value) {
var rejectObj = {
null: true,
undefined: true,
NaN: true,
0: true,
false: true,
'': true
};
return rejectObj[value] ? false : true;
}
//Apply Styles
var formatText = {
allignContent: function(value, alignValue, noValue) {
alignValue = assignDefaultValue(alignValue, 'center');
noValue = assignDefaultValue(noValue, '-');
return '<p align="' + alignValue + '">' + assignDefaultValue(value, noValue) + '</p>';
},
applyStyle: function(param) {
var str = '<span style="';
if (param.FONT_WEIGHT)
str += 'font-weight:' + param.FONT_WEIGHT + ';';
if (param.FONT_COLOR)
str += 'color:' + param.FONT_COLOR + ';';
if (param.FONT_SIZE)
str += 'font-size:' + param.FONT_SIZE + ';';
if (param.FONT_STYLE)
str += 'font-style:' + param.FONT_STYLE + ';';
if (param.FONT_FAMILY)
str += 'font-family:' + param.FONT_FAMILY + ';';
str += '"> ' + param.value + ' </span>';
return str;
}
};
for (var key in formatText) {
if (typeof formatText[key] === 'function') {
formatText[key] = trycatch(formatText[key], 'formatText.' + key);
}
}
//WooCommerce REST API Calls for Product Management
var wooCommerceAPIObj = {
listProducts: function(domain_url, auth, pageIndex) {
var request_url = url.format({
domain: domain_url + '/wp-json/wc/v2/products',
params: {
per_page: '100',
page: assignDefaultValue(pageIndex, 1),
status: 'publish'
}
});
log.debug('request_url', request_url);
var response = https.get({
url: request_url,
headers: { authorization: auth }
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
},
fetchProduct: function(domain_url, auth, id) {
var response = https.get({
url: domain_url + '/wp-json/wc/v2/products/' + id,
headers: { authorization: auth }
});
return JSON.parse(response.body);
},
updateProduct: function(domain_url, auth, bodyObj) {
var response = https.put({
url: domain_url + '/wp-json/wc/v2/products/' + id,
headers: { authorization: auth },
body: JSON.stringify(bodyObj)
});
return {
header: response.headers,
body: JSON.parse(response.body)
};
}
};
for (var key in wooCommerceAPIObj) {
if (typeof wooCommerceAPIObj[key] === 'function') {
wooCommerceAPIObj[key] = trycatch(wooCommerceAPIObj[key], 'wooCommerceAPIObj.' + key);
}
}
var main = {
searchForInventoryItem: function(pageIndexField, pageIndex, pageLimit) {
var responseObj = {};
var inventoryitemSearchObj = search.create({
type: "inventoryitem",
filters: [
["isinactive", "is", "F"],
"AND",
["type", "anyof", "InvtPart"],
"AND",
["caption", "isnotempty", ""]
"AND",
["internalid", "anyof", "9460"]
],
columns: [
search.createColumn({
name: "internalid",
summary: "GROUP",
label: "Internal ID"
}),
search.createColumn({
name: "itemid",
summary: "MAX",
label: "Name"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityonhand},0)",
label: "Formula (Numeric)"
}),
search.createColumn({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityavailable},0)",
label: "Formula (Numeric)"
}),
search.createColumn({
name: "storedisplayname",
summary: "GROUP",
sort: search.Sort.ASC,
label: "Store Display Name"
})
]
});
var searchResultCount = inventoryitemSearchObj.runPaged().count;
log.debug("inventoryitemSearchObj result count", searchResultCount);
inventoryitemSearchObj.run().each(function(result) {
// .run().each has a limit of 4,000 results
responseObj[result.getValue({
name: "storedisplayname",
summary: "GROUP",
label: "Store Display Name"
})] = {
internalid: result.getValue({
name: "internalid",
summary: "GROUP",
label: "Internal ID"
}),
itemid: result.getValue({
name: "itemid",
summary: "MAX",
label: "Name"
}),
sku: result.getValue({
name: "storedisplayname",
summary: "GROUP",
label: "Store Display Name"
}),
quantityonhand: result.getValue({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityonhand},0)",
label: "Formula (Numeric)"
}),
quantityavailable: result.getValue({
name: "formulanumeric",
summary: "SUM",
formula: "NVL({locationquantityavailable},0)",
label: "Formula (Numeric)"
})
};
return true;
});
for (var i = 1, j = parseInt(pageLimit); i <= j; i++) {
pageIndexField.addSelectOption({
value: i,
text: i + ' of ' + j + ' Pages'
});
}
return responseObj;
},
generateForm: function(context) {
log.debug('generateForm', 'generateForm');
//Getting the filter values;
var pageIndex = assignDefaultValue(context.request.parameters.pageindex, 1);
//initialize form
var form = serverWidget.createForm({
title: 'WooCommerce Items'
});
//https://system.na1.netsuite.com/app/common/media/mediaitem.nl?id=563061
form.clientScriptFileId = 563061;
//Page Index
var pageIndexField = form.addField({
id: 'pageindexfield',
type: serverWidget.FieldType.SELECT,
label: 'Page Index'
});
pageIndexField.defaultValue = pageIndex;
//Total WooCommerce Items per Page
var wooCommerceItemCount = form.addField({
id: 'custpage_totalitemsperpage',
type: serverWidget.FieldType.TEXT,
label: 'WooCoomerce Items Count'
});
wooCommerceItemCount.updateDisplayType({
displayType: serverWidget.FieldDisplayType.DISABLED
});
//WooCommerce Authorisation Details
var WOOCOMMERCE_AUTH = [{
Website_URL: 'https://www.iloveblvd.com',
API_Name: 'JJ NS-WC Inventory Sync',
API_Authorization: 'Basic Y2tfODY5ZWYyZTllNWYzYmZjNTM0NGE4ZjlmNjkzNGJmZWMzNjk2N2UzNjpjc18zZTMzZTFhODk0MjgxMTk2YzMxYTIxY2ZkOGUzNTE1MzNlMWE0Mzky',
Consumer_Key: 'ck_869ef2e9e5f3bfc5344a8f9f6934bfec36967e36',
Consumer_Secret: 'cs_3e33e1a894281196c31a21cfd8e351533e1a4392'
}];
WOOCOMMERCE_AUTH.forEach(function(api, api_index) {
var sendAnotherRequest = true;
var listProducts, wc_url, wc_auth, pageLimit,
productArray = [],
skuArray = [],
mapObj = {};
log.debug('PROCCESSING FOR ', api.Website_URL);
// log.debug('api ', api);
wc_url = api.Website_URL;
wc_auth = api.API_Authorization;
listProducts = wooCommerceAPIObj.listProducts(wc_url, wc_auth, pageIndex);
// var fullarray = [].concat.apply([], array);
// productArray = productArray.concat.apply([], listProducts.body);
// productArray = productArray.concat.apply(productArray, listProducts.body);
productArray = productArray.concat(listProducts.body);
pageLimit = parseInt(listProducts.header['X-WP-TotalPages']);
log.debug('Final productArray.length', productArray.length);
//log.debug('productArray', productArray);
var itemSearchObj = main.searchForInventoryItem(pageIndexField, pageIndex, pageLimit);
productArray.forEach(function(eachProduct) {
if (eachProduct.sku)
mapObj[eachProduct.sku] = {
WooComerce: {
id: eachProduct.id,
sku: eachProduct.sku,
stock_quantity: eachProduct.stock_quantity,
in_stock: eachProduct.in_stock
},
NetSuite: itemSearchObj[eachProduct.sku]
};
});
log.debug('mapObj ', mapObj);
log.debug('Object.keys(mapObj) ', Object.keys(mapObj));
log.debug('Object.keys(mapObj).length ', Object.keys(mapObj).length);
if (checkForParameter(mapObj)) {
wooCommerceItemCount.defaultValue = Object.keys(mapObj).length + ' items on Page ' + pageIndex;
var itemSublist = form.addSublist({
id: 'custpage_itemlist',
type: serverWidget.SublistType.LIST,
label: 'Item List'
});
itemSublist.addField({ id: 'custpage_01', label: 'WC SKU', type: serverWidget.FieldType.TEXT, align: serverWidget.LayoutJustification.LEFT });
itemSublist.addField({ id: 'custpage_02', label: 'WC ID', type: serverWidget.FieldType.TEXT, align: serverWidget.LayoutJustification.LEFT });
itemSublist.addField({ id: 'custpage_03', label: 'WC Stock QTY', type: serverWidget.FieldType.TEXT, align: serverWidget.LayoutJustification.LEFT });
itemSublist.addField({ id: 'custpage_04', label: 'WC Stock Status', type: serverWidget.FieldType.TEXT });
itemSublist.addField({ id: 'custpage_05', label: 'NS ID', type: serverWidget.FieldType.TEXT });
itemSublist.addField({ id: 'custpage_06', label: 'NS Item', type: serverWidget.FieldType.TEXT });
itemSublist.addField({ id: 'custpage_07', label: 'NS Quantity Available', type: serverWidget.FieldType.TEXT });
itemSublist.addField({ id: 'custpage_08', label: 'Proposed Action', type: serverWidget.FieldType.TEXT });
for (var index = 0, len = Object.keys(mapObj).length; index < len; index++) {
//WooCommerce
itemSublist.setSublistValue({
id: 'custpage_01',
value: assignDefaultValue(mapObj[Object.keys(mapObj)[index]].WooComerce.sku, " - "),
line: index
});
itemSublist.setSublistValue({
id: 'custpage_02',
value: assignDefaultValue(parseInt(mapObj[Object.keys(mapObj)[index]].WooComerce.id).toString(), " - "),
line: index
});
itemSublist.setSublistValue({
id: 'custpage_03',
value: assignDefaultValue(
formatText.applyStyle({
value: mapObj[Object.keys(mapObj)[index]].WooComerce.stock_quantity,
FONT_COLOR: mapObj[Object.keys(mapObj)[index]].WooComerce.stock_quantity ? 'green' : 'red',
FONT_WEIGHT: '100'
}),
formatText.applyStyle({
value: 'null',
FONT_COLOR: 'red',
FONT_WEIGHT: '100'
})
),
line: index
});
itemSublist.setSublistValue({
id: 'custpage_04',
value: assignDefaultValue(
formatText.applyStyle({
value: mapObj[Object.keys(mapObj)[index]].WooComerce.in_stock,
FONT_COLOR: (mapObj[Object.keys(mapObj)[index]].WooComerce.in_stock) ? 'green' : 'red',
FONT_WEIGHT: '100'
}),
formatText.applyStyle({
value: 'false',
FONT_COLOR: 'red',
FONT_WEIGHT: '100'
})
),
line: index
});
//NetSuite
if (checkForParameter(mapObj[Object.keys(mapObj)[index]].NetSuite)) {
itemSublist.setSublistValue({
id: 'custpage_05',
value: assignDefaultValue(mapObj[Object.keys(mapObj)[index]].NetSuite.internalid, " - "),
line: index
});
itemSublist.setSublistValue({
id: 'custpage_06',
value: assignDefaultValue(mapObj[Object.keys(mapObj)[index]].NetSuite.itemid, " - "),
line: index
});
itemSublist.setSublistValue({
id: 'custpage_07',
value: assignDefaultValue(
formatText.applyStyle({
value: mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable,
FONT_COLOR: rejectThisValues(mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable) ? 'green' : 'red',
FONT_WEIGHT: '100'
}),
formatText.applyStyle({
value: '0',
FONT_COLOR: 'red',
FONT_WEIGHT: '100'
})
),
line: index
});
//if (itemSublist.getSublistValue({ id: 'custpage_07', line: index }) && itemSublist.getSublistValue({ id: 'custpage_07', line: index }) != 0)
if (mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable > 0 && mapObj[Object.keys(mapObj)[index]].WooComerce.in_stock == true && mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable == mapObj[Object.keys(mapObj)[index]].WooComerce.stock_quantity)
itemSublist.setSublistValue({
id: 'custpage_08',
value: formatText.applyStyle({
value: 'No Action Required',
FONT_COLOR: 'grey',
FONT_WEIGHT: '600'
}),
line: index
});
else if (mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable == 0 && mapObj[Object.keys(mapObj)[index]].WooComerce.in_stock == false && mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable == mapObj[Object.keys(mapObj)[index]].WooComerce.stock_quantity)
itemSublist.setSublistValue({
id: 'custpage_08',
value: formatText.applyStyle({
value: 'No Action Required',
FONT_COLOR: 'grey',
FONT_WEIGHT: '600'
}),
line: index
});
else if (rejectThisValues(mapObj[Object.keys(mapObj)[index]].NetSuite.quantityavailable))
itemSublist.setSublistValue({
id: 'custpage_08',
value: "set " + formatText.applyStyle({ value: 'in_stock = true', FONT_COLOR: 'green' }) + " <br> " +
"set " + formatText.applyStyle({
value: 'stock_quantity = ' + itemSublist.getSublistValue({ id: 'custpage_07', line: index }),
FONT_COLOR: 'green'
}) + " <br> " +
formatText.applyStyle({
value: 'ie ITEM IS IN STOCK',
FONT_COLOR: 'green',
FONT_WEIGHT: '600'
}),
line: index
});
else
itemSublist.setSublistValue({
id: 'custpage_08',
value: "set " + formatText.applyStyle({ value: 'in_stock = false', FONT_COLOR: 'red' }) + " <br> " +
"set " + formatText.applyStyle({
value: 'stock_quantity = ' + itemSublist.getSublistValue({ id: 'custpage_07', line: index }),
FONT_COLOR: 'red'
}) + " <br> " +
formatText.applyStyle({
value: 'ie ITEM IS OUT OF STOCK',
FONT_COLOR: 'red',
FONT_WEIGHT: '600'
}),
line: index
});
} else {
itemSublist.setSublistValue({ id: 'custpage_05', value: assignDefaultValue(" - ", " - "), line: index });
itemSublist.setSublistValue({ id: 'custpage_06', value: assignDefaultValue(" - ", " - "), line: index });
itemSublist.setSublistValue({ id: 'custpage_07', value: assignDefaultValue(" - ", " - "), line: index });
itemSublist.setSublistValue({
id: 'custpage_08',
value: formatText.applyStyle({ value: ' Item Not Mapped ', FONT_COLOR: 'red', FONT_WEIGHT: '600' }),
line: index
});
}
}
}
});
return form;
},
onRequest: function(context) {
if (context.request.method === 'GET') {
var form = main.generateForm(context);
context.response.writePage(form);
}
}
};
for (var key in main) {
if (typeof main[key] === 'function') {
main[key] = trycatch(main[key], key);
}
}
function trycatch(myfunction, key) {
return function() {
try {
return myfunction.apply(this, arguments);
} catch (e) {
log.debug("error in main." + key, e);
// log.error("error in main." + key, e);
return false;
}
};
}
return main;
});