Requirement:
We need to be able to sell through data.
By any date range we want By any dealer?
Can it fetch daily and add it and we can analyze all that data through a saved search?
We will use the 8 digit UID to filter different stores .
Take all the sell thru data and add it to the custom record, so everything is searchable.
Solution
/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
/************************************************************************************************
* * Balaji Trading Network | BTN-2043 | i@mertix Integration
* **********************************************************************************************
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 24.02.2022
*
* REVISION HISTORY
*
***********************************************************************************************/
define(['N/config', 'N/error', 'N/file', 'N/format', 'N/http', 'N/https', 'N/log', 'N/record', 'N/runtime', 'N/search', 'N/task', 'N/xml', '/SuiteScripts/Jobin and Jismi IT Services/BTN-2043/convertXMLtoJSON.js'],
/**
* @param{config} config
* @param{error} error
* @param{file} file
* @param{format} format
* @param{http} http
* @param{https} https
* @param{log} log
* @param{record} record
* @param{runtime} runtime
* @param{search} search
* @param{task} task
* @param{xml} xml
* @param{}
*/
(config, error, file, format, http, https, log, record, runtime, search, task, xml,xml_json) => {
const xmlToJSON = xml_json.Test;
/**
* function to search if the iQmetrix customet detail custom record already exists for a RQ company ID
* returns search result count
*/
function customRecordEntryExist_Search(type, Id, criteria) {
try {
var customrecord_jj_iqmetrix_integrationSearchObj = search.create({
type: type,
filters:
[
[criteria, "is", Id]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"})
]
});
var searchResultCount = customrecord_jj_iqmetrix_integrationSearchObj.runPaged().count;
// log.debug("SearchObj result count", searchResultCount);
if (searchResultCount > 0){
var internalId;
customrecord_jj_iqmetrix_integrationSearchObj.run().each(function(result) {
internalId = result.getValue({name: "internalid", label: "Internal ID"})
return true;
});
return internalId;
}
else
return false;
} catch (e) {
log.debug("Error@iQmetrixCustDetailIsExist_Search", e)
return false;
}
}
/**
* search to get the custom child record Customer Store Detail's id
* returns record internal id
*/
function customerStoreRecIdSearch(externalid){
try{
var customrecord_cust_storedetail_btn2043SearchObj = search.create({
type: "customrecord_cust_storedetail_btn2043",
filters:
[
["custrecord_jj_externalid_btn2043","is", externalid]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"})
]
});
var internalid;
var searchResultCount = customrecord_cust_storedetail_btn2043SearchObj.runPaged().count;
// log.debug("customrecord_cust_storedetail_btn2043SearchObj result count",searchResultCount);
if (searchResultCount > 0) {
customrecord_cust_storedetail_btn2043SearchObj.run().each(function (result) {
internalid = result.getValue({name: "internalid", label: "Internal ID"})
return true;
});
return internalid;
}
else
return false;
}catch (e) {
log.debug("customerStoreRecIdSearch", e)
return false;
}
}
/**
* function to create iQmetrix customet detail custom record
* returns iQmetrix customet detail custom record id
*/
function createIQmetrixCustDetailRec(rqCompanyId, customer) {
try {
var iQmetrixRec = record.create({
type: 'customrecord_jj_iqmetrix_integration',
isDynamic: true
});
//last execution date
var d = new Date();
d.setDate(d.getDate() + 1);
var date = formatDate(d);
iQmetrixRec.setValue('name', rqCompanyId);
iQmetrixRec.setValue('custrecord_jj_clientname_btn2043', customer);
iQmetrixRec.setValue('custrecord_jj_rqcompanyid_btn2043', rqCompanyId);
iQmetrixRec.setValue('externalid', customer);
var iQmetrixRecID = iQmetrixRec.save();
return iQmetrixRecID;
} catch (e) {
log.debug("Error@createIQmetrixCustDetailRec", e)
return false;
}
}
/**
* function to create Customer store detail custom record
* returns Customer store detail custom record id
*/
function createCustomerStoreRec(dataObj){
try{
var customRec = record.load({ type: 'customrecord_jj_iqmetrix_integration', id: dataObj.parentrecord, isDynamic: true });
var exernalid = dataObj.customerid+"_"+dataObj.storeid;
var sublistLines = customRec.getLineCount({
sublistId: 'recmachcustrecord_clientdetail_btn2043'
})
customRec.insertLine({ sublistId: 'recmachcustrecord_clientdetail_btn2043', line: sublistLines });
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_clientdetail_btn2043', value: dataObj.parentrecord});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_storename_btn2043', value: dataObj.storename});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_storeid_btn2043', value: dataObj.storeid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_uid_customer_btn2043', value: dataObj.UID});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_vendoracc_num_2043', value: dataObj.vendoraccountnumber});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_externalid_btn2043', value: exernalid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_clientdetail_btn2043', fieldId: 'custrecord_jj_customer_storedetl_btn2043', value: dataObj.customerid});
customRec.commitLine({ sublistId: 'recmachcustrecord_clientdetail_btn2043'});
customRec.save();
//search to get custom record id
var id = customerStoreRecIdSearch(exernalid);
return id;
}catch (e) {
log.debug("Error@createCustomerStoreRec", e)
return false;
}
}
/**
* function to create Item sales data custom record
* returns Item sales data custom record id
*/
function createItemSalesRecord(parentID, customer, store, detailArr){
try{
var customRec = record.load({ type: 'customrecord_cust_storedetail_btn2043', id: parentID, isDynamic: true });
var soldon = new Date(detailArr.soldon)/1000;
// log.debug("soldon", soldon)
var externalid = customer+"_"+(checkObjIsEmpty(detailArr.rqinvoiceidbystore)?"":detailArr.rqinvoiceidbystore) +"_"+(checkObjIsEmpty(detailArr.vendorsku)?"":detailArr.vendorsku)+"_"+(checkObjIsEmpty(detailArr.productsku)?"":detailArr.productsku)+"_"+(checkObjIsEmpty(detailArr.channelid)?"":detailArr.channelid)+"_"+ (new Date((checkObjIsEmpty(detailArr.soldon)?"":detailArr.soldon))/1000) +"_"+ (checkObjIsEmpty(detailArr.productitemid)?"":detailArr.productitemid)+"_"+ (checkObjIsEmpty(detailArr.invoicedby)?"":detailArr.invoicedby)+"_"+ (checkObjIsEmpty(detailArr.storeid)?"":detailArr.storeid)+"_"+ (checkObjIsEmpty(detailArr.districtname)?"":detailArr.districtname)+"_"+ (checkObjIsEmpty(detailArr.districtid)?"":detailArr.districtid)+"_"+ (checkObjIsEmpty(detailArr.regionname)?"":detailArr.regionname)+"_"+ (checkObjIsEmpty(detailArr.regionid)?"":detailArr.regionid)+"_"+ (checkObjIsEmpty(detailArr.channelname)?"":detailArr.channelname)+"_"+ (checkObjIsEmpty(detailArr.description)?"":detailArr.description)+"_"+ (checkObjIsEmpty(detailArr.listprice)?"":detailArr.listprice);
// log.debug("externalid",externalid)
//convert the sold on date to m/d/yyyy format
var soldOnDate = new Date(detailArr.soldon);
soldOnDate.setDate(soldOnDate.getDate());
// log.debug("soldOnDate", soldOnDate)
var sublistLines = customRec.getLineCount({
sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043'
})
customRec.insertLine({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', line: sublistLines });
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_customer_store_btn2043', value: customer});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_storeid_store_btn2043', value: store});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_salesreport_store_btn2043', value: detailArr.rqinvoiceidbystore});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_vendorsku_btn2043', value: detailArr.vendorsku});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_productsku_btn2043', value: detailArr.productsku});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_invoicedby_btn2043', value: detailArr.invoicedby});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_districtname_btn2043', value: detailArr.districtname});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_districtid_btn2043', value: detailArr.districtid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_regionname_btn2043', value: detailArr.regionname});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_regionid_btn2043', value: detailArr.regionid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_channelname_btn2043', value: detailArr.channelname});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_channelid_btn_2043', value: detailArr.channelid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_soldon_btn_2043', value: soldOnDate});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_productitemid_btn2043', value: detailArr.productitemid});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_description_btn2043', value: detailArr.description});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_quantity_btn2043', value: detailArr.quantity});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_listprice_btn2043', value: detailArr.listprice});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_refund_btn2043', value: detailArr.refund});
customRec.setCurrentSublistValue({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043', fieldId: 'custrecord_jj_externalid_sales_btn2043', value: externalid});
customRec.commitLine({ sublistId: 'recmachcustrecord_jj_parentrecord_store_btn2043'});
customRec.save();
}catch (e) {
log.debug("Error@createItemSalesRecord", e)
return false;
}
}
/**
* This function helps to identify the null values or not.
**/
function checkForParameter(parameter, parameterName) {
if (parameter != "" && parameter != null && parameter != undefined && parameter != "undefined" && parameter != " " && parameter != false) {
return true;
} else {
return false;
}
}
/**
* API CALLS for iQmetrix
* - GetStoreList
* -GetInventory
*/
function GetStoreList(urlPath, vendorID, userName, passWord, CompanyID) {
try {
var SOAP_REQUEST = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soap:Body> <GetStoreList xmlns="http://www.iqmetrix.com"> <Vendor> <VendorID>' + vendorID + '</VendorID> <Username>' + userName + '</Username> <Password>' + passWord + '</Password> <Client> <ClientID>' + CompanyID + '</ClientID> </Client> </Vendor> </GetStoreList> </soap:Body></soap:Envelope>';
var response = https.post({
url: urlPath,
headers: {
'Content-Type': 'text/xml;charset=UTF-8',
},
body: SOAP_REQUEST
});
// log.debug("response", response);
if (response.code == 200) {
if (checkForParameter(((response.body).toString()).split("<StoreInformation>")[1], '<StoreInformation>")[1]')) {
return xmlToJSON.xmltag2json(response.body, 'GetStoreListResult');
} else {
return {};
}
} else {
return {};
}
} catch (e) {
log.debug("Error@GetStoreList function", e);
return {};
}
}
function GetInventoryDetails(urlPath, vendorID, vendorUserName, vendorPassword, CompanyID, storeID, startDate, endDate){
try {
var SOAP_REQUEST ='<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soap:Body><GetProductSalesReport xmlns="http://www.iqmetrix.com"><Vendor><VendorID>'+ vendorID +'</VendorID><Username>'+ vendorUserName +'</Username><Password>'+ vendorPassword +'</Password><Client><ClientID>'+ CompanyID +'</ClientID></Client></Vendor><storeId>' + storeID + '</storeId><startDate>' + startDate + '</startDate><endDate>'+ endDate +'</endDate></GetProductSalesReport></soap:Body></soap:Envelope>';
var response = https.post({
url: urlPath,
headers: {
'Content-Type': 'text/xml;charset=UTF-8',
},
body: SOAP_REQUEST
});
// log.debug("response", response);
if (response.code == 200) {
if (checkForParameter(((response.body).toString()).split("<ProductSalesReportData>")[1], '<ProductSalesReportData>")[1]')) {
return xmlToJSON.xmltag2json(response.body, 'GetProductSalesReportResult');
} else {
return {};
}
} else {
return {};
}
} catch (e) {
log.debug("Error@GetStoreList function", e);
return {};
}
}
/**
* This function helps to store the IQ METRICS Credentials
**/
function clientCredentials() {
try {
var credentialObj = {
'vendorID': //vendor id,
'vendorUserName': //vendor username,
'vendorPassword': //password,
'GetInventoryUrl': 'https://vmi3.iqmetrix.net/VMIService.asmx?op=GetInventoryReport',
'GetStoreListURL': 'https://vmi3.iqmetrix.net/VMIService.asmx?op=GetStoreList'
}
return credentialObj;
} catch (error) {
log.debug('error @ clientCredentials', error)
}
}
/**
* This function helps to get array unique UID_CRK of a customer
**/
function getUID_CRK_Search(customerID){
try {
var customerSearchObj = search.create({
type: "customer",
filters:
[
["internalid","anyof",customerID]
],
columns:
[
search.createColumn({
name: "address3",
join: "Address",
label: "Address 3"
})
]
});
var uid_crk, uid_crkArray=[];
var searchResultCount = customerSearchObj.runPaged().count;
// log.debug("customerSearchObj result count",searchResultCount);
if (searchResultCount>0) {
customerSearchObj.run().each(function (result) {
uid_crk = result.getValue({
name: "address3",
join: "Address",
label: "Address 3"
})
if (uid_crk)
uid_crkArray.push(uid_crk)
return true;
});
uid_crkArray = uid_crkArray.filter(function (item, index, uid_crkArray) {
return uid_crkArray.indexOf(item) == index;
});
return uid_crkArray;
}
else
return [];
}catch (e) {
log.debug("Error@getUID_CRKfromAddressbook", e)
return [];
}
}
/** function for formatting date
* @param d
* @returns date in mm/dd/yyyy format
*/
function formatDate(d) {
try {
if (!d) return null;
var date = d.getDate(), month = d.getMonth(), year = d.getFullYear();
return addZero(month + 1) + "/" + addZero(date) + "/" + year;
}catch (e) {
log.debug("Error@formatDate", e)
}
}
function addZero(val) {
try {
return val<10? "0"+val: val;
} catch (e) {
log.debug("error@addZero", e)
}
}
/** function to check if an object is empty
* @param obj
* @returns true/false
*/
function checkObjIsEmpty(obj){
try{
if(Object.keys(obj).length === 0 && obj.constructor === Object)
return true;
else
return false;
}catch (e) {
log.debug("checkObjEmpty", checkObjEmpty)
}
}
function inventorySalesReport(dataObj, parseArray, custStoreRecID, storeID, array, index){
try{
//check if the custom record already exists
var uniqueExtId = dataObj.customerid+"_"+(checkObjIsEmpty(parseArray.rqinvoiceidbystore)?"":parseArray.rqinvoiceidbystore) +"_"+(checkObjIsEmpty(parseArray.vendorsku)?"":parseArray.vendorsku)+"_"+(checkObjIsEmpty(parseArray.productsku)?"":parseArray.productsku)+"_"+(checkObjIsEmpty(parseArray.channelid)?"":parseArray.channelid)+"_"+ (new Date((checkObjIsEmpty(parseArray.soldon)?"":parseArray.soldon))/1000) +"_"+ (checkObjIsEmpty(parseArray.productitemid)?"":parseArray.productitemid)+"_"+ (checkObjIsEmpty(parseArray.invoicedby)?"":parseArray.invoicedby)+"_"+ (checkObjIsEmpty(parseArray.storeid)?"":parseArray.storeid)+"_"+ (checkObjIsEmpty(parseArray.districtname)?"":parseArray.districtname)+"_"+ (checkObjIsEmpty(parseArray.districtid)?"":parseArray.districtid)+"_"+ (checkObjIsEmpty(parseArray.regionname)?"":parseArray.regionname)+"_"+ (checkObjIsEmpty(parseArray.regionid)?"":parseArray.regionid)+"_"+ (checkObjIsEmpty(parseArray.channelname)?"":parseArray.channelname)+"_"+ (checkObjIsEmpty(parseArray.description)?"":parseArray.description)+"_"+ (checkObjIsEmpty(parseArray.listprice)?"":parseArray.listprice);
var itemSalesExist = customRecordEntryExist_Search("customrecord_jj_itemsalesreport_btn2043", uniqueExtId, "custrecord_jj_externalid_sales_btn2043"); //"custrecord_jj_externalid_sales_btn2043"
if (itemSalesExist === false)
//create custom record "item sales report"
var itemSalesRec = createItemSalesRecord(custStoreRecID, dataObj.customerid, storeID, parseArray)
else {
//if the IQitem sales report custom record already exists, add the item quatity to the existing records qty
// log.debug("itemSalesExist", itemSalesExist)
var qty = parseArray.quantity;
var existingQty = search.lookupFields({
type: 'customrecord_jj_itemsalesreport_btn2043',
id: itemSalesExist,
columns: ['custrecord_jj_quantity_btn2043']
});
if (qty)
record.submitFields({
type: 'customrecord_jj_itemsalesreport_btn2043',
id: itemSalesExist,
values: {
custrecord_jj_quantity_btn2043: Number(existingQty.custrecord_jj_quantity_btn2043) + Number(qty)
},
options: {
enableSourcing: false,
ignoreMandatoryFields : true
}
});
}
//remove the processed array element from array
if ((index > -1) && array.length>0) {
array.splice(index, 1);
log.debug("array", array)
return array;
}
}catch (e) {
log.debug("Error@inventorySalesReport", e)
}
}
const getInputData = (inputContext) => {
try {
var resultsArr = [];
var iQmetrixCustSearch = search.load({
id: 'customsearch_jj_iqmetrix_intgrn_btn2043'
})
var searchResult = iQmetrixCustSearch.run();
searchResult.each(function (result) {
var allSearchValues = result.getAllValues();
resultsArr.push(allSearchValues);
return true;
});
log.debug("resultsArr", resultsArr)
if (resultsArr.length <=0)
return;
var custRec = resultsArr[0].internalid[0].value;
var rqCompanyId = resultsArr[0].custentity_jj_btn_602_rq_company_id;
let custDetailExist = customRecordEntryExist_Search("customrecord_jj_iqmetrix_integration", custRec, "externalid");
// log.debug("custDetailExist", custDetailExist)
//if the iQmetrix customerdetail custom record already exists for a customer;
var iQmetrixRecId;
if (custDetailExist){
iQmetrixRecId = custDetailExist;
}
else {
//create custom record iQmetrix customerdetail
iQmetrixRecId = createIQmetrixCustDetailRec(rqCompanyId, custRec);
//var uid_crkArray = iQmetrixReturnArr[1];
}
//check the Executed check box in customer record on creation of iQmetrix customerdetail custom record
var saveId = record.submitFields({
type: record.Type.CUSTOMER,
id: custRec,
values: {
custentity_jj_executed_btn2043: true
}
});
// log.debug("iQmetrixRecId", iQmetrixRecId)
//get the uid crk values of the customer
var uid_crkArray = getUID_CRK_Search(custRec)
log.debug("uid_crkArray", uid_crkArray)
//set the uid crk value in the iQmetric customerdetail custom record.
record.submitFields({
type: "customrecord_jj_iqmetrix_integration",
id: iQmetrixRecId,
values: {
custrecord_jj_uid_btn2043: uid_crkArray.toString()
}
});
//getting the store information data using storelist API call.
var getStoreListCredentials = clientCredentials();
var vendorID = getStoreListCredentials.vendorID;
var vendorUserName = getStoreListCredentials.vendorUserName;
var vendorPassword = getStoreListCredentials.vendorPassword;
var ClientID = rqCompanyId;
var GetStoreListURL = getStoreListCredentials.GetStoreListURL;
var processData = GetStoreList(GetStoreListURL, vendorID, vendorUserName, vendorPassword, ClientID);
// log.debug(typeof processData)
if (Object.keys(processData).length) {
var parseArray = processData.storeinformation;
//check if each store id in uid_cr is active
var activeStoreArr = [];
for (let i=0; i<uid_crkArray.length; i++){
for (let j=0; j<parseArray.length; j++){
var activeStoreObj = {};
var vendoraccountnumber = parseArray[j].vendoraccountnumber;
if (vendoraccountnumber.includes(uid_crkArray[i])) {
activeStoreObj.UID = uid_crkArray[i];
activeStoreObj.vendoraccountnumber = vendoraccountnumber;
activeStoreObj.clientId = rqCompanyId;
activeStoreObj.storeid = parseArray[j].storeid;
activeStoreObj.storename = parseArray[j].name;
activeStoreObj.parentrecord = iQmetrixRecId;
activeStoreObj.customerid = custRec;
// activeStoreObj.lastupdateddate = lastUpdatedDate.custrecord_jj_lastdate_btn2043;
activeStoreArr.push(activeStoreObj);
}
}
}
// log.debug("activeStoreArr",activeStoreArr)
return activeStoreArr;
}
else
return [];
} catch
(e)
{
log.debug("Error@getInputData", e)
return [];
}
}
const reduce = (reduceContext) => {
try{
var startExecutionTime = new Date().getTime();
var custStoreRecID, endDate;
let dataObj = JSON.parse(reduceContext.values);
// log.debug("dataObj", dataObj)
if (dataObj){
var uniqueID = dataObj.customerid+"_"+dataObj.storeid;
// log.debug("uniqueID", uniqueID)
//check if the custom record already exist to avoid duplication
var customRec2Exist = customRecordEntryExist_Search("customrecord_cust_storedetail_btn2043", uniqueID, "custrecord_jj_externalid_btn2043" ); //custrecord_jj_externalid_btn2043
// log.debug("customRec2Exist", customRec2Exist)
if (customRec2Exist)
custStoreRecID = customRec2Exist;
else
//creating custom record "Customer store detail"
custStoreRecID = createCustomerStoreRec(dataObj);
//last execution date from customer store details custom record
var lastUpdatedDate = search.lookupFields({
type: 'customrecord_cust_storedetail_btn2043',
id: custStoreRecID,
columns: ['custrecord_jj_lastdate_store_btn2043']
});
var startDate;
if (lastUpdatedDate.custrecord_jj_lastdate_store_btn2043) {
startDate = new Date(lastUpdatedDate.custrecord_jj_lastdate_store_btn2043);
startDate.setDate(startDate.getDate() + 1);
startDate= formatDate(startDate);
}
else
startDate = Number(new Date((new Date().setDate(new Date().getDate()))).getMonth() + 1)+ '/' + new Date((new Date().setDate(new Date().getDate()-1))).getDate()+'/'+new Date((new Date().setDate(new Date().getDate()))).getFullYear();
endDate = Number(new Date((new Date().setDate(new Date().getDate()))).getMonth() + 1)+ '/' + new Date((new Date().setDate(new Date().getDate()-1))).getDate()+'/'+new Date((new Date().setDate(new Date().getDate()))).getFullYear();
// log.debug("last updated date", lastUpdatedDate.custrecord_jj_lastdate_store_btn2043)
// log.debug("startDate", startDate)
// log.debug("endDate", endDate)
//get the inventory details of each store by calling getinventory API endpoint
var getStoreListCredentials = clientCredentials();
var vendorID = getStoreListCredentials.vendorID; ``
var vendorUserName = getStoreListCredentials.vendorUserName;
var vendorPassword = getStoreListCredentials.vendorPassword;
var ClientID = dataObj.clientId ;
var GetInventoryUrl = getStoreListCredentials.GetInventoryUrl;
var storeID = dataObj.storeid;
var processData = GetInventoryDetails(GetInventoryUrl, vendorID, vendorUserName, vendorPassword, ClientID, storeID, startDate, endDate);
if (Object.keys(processData).length) {
var parseArray = processData.productsalesreportdata;
log.debug("parsearray", parseArray)
if (parseArray.constructor == Object)
inventorySalesReport(dataObj, parseArray, custStoreRecID, storeID, '', '')
else {
for (var i = 0; i < parseArray.length; i = 0) {
//check execution limit
var currentExecutionTime = new Date().getTime();
var governanceUsage = Number(runtime.getCurrentScript().getRemainingUsage())
log.debug("governanceUsage", governanceUsage)
//Calculate the Time Elapsed between End Time and Start Time
var timeElapsed = (currentExecutionTime * 0.001) - (startExecutionTime * 0.001);
log.debug('timeElapsed', timeElapsed);
if (timeElapsed > 700 || governanceUsage < 250 ) {
var FileNew = file.create({
name: new Date()/1000+'.txt',
fileType: file.Type.PLAINTEXT,
folder: 1666904,
contents: JSON.stringify({'array': parseArray, 'data':{'dataObj':dataObj, 'custStoreRecID':custStoreRecID, 'storeId':storeID }})
});
FileNew.save();
break;
}
parseArray = inventorySalesReport(dataObj, parseArray[i], custStoreRecID, storeID, parseArray, i);
}
}
}
//update last updated date
//var lastDate = Number(new Date((new Date().setDate(new Date().getDate()))).getMonth() + 1)+ '/' + new Date((new Date().setDate(new Date().getDate()-1))).getDate()+'/'+new Date((new Date().setDate(new Date().getDate()))).getFullYear();
// log.debug('lastDate', lastDate)
record.submitFields({
type: 'customrecord_cust_storedetail_btn2043',
id: custStoreRecID,
values: {
custrecord_jj_lastdate_store_btn2043:endDate
},
options: {
enableSourcing: false,
ignoreMandatoryFields : true
}
});
}
}catch (e) {
log.debug("Error@reduce", e)
}
}
const summarize = (summaryContext) => {
try{
var scriptTask, scriptTaskId;
var searchCount = search.load({id: 'customsearch_jj_iqmetrix_intgrn_btn2043'}).runPaged().count;
// log.debug("searchCount",searchCount)
if (searchCount>0){
//reschedule the MR script
scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_jj_iqmetrix_intgrn_btn2043';
scriptTask.deploymentId = 'customdeploy_jj_iqmetrix_intgrn_btn2043';
scriptTaskId = scriptTask.submit();
}
else {
// schedule the MR script that executes for the datas stored in filecabinet due to execution limit exceeded error
var scriptTask_file = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask_file.scriptId = 'customscript_jj_handle_executionlimit';
scriptTask_file.deploymentId = 'customdeploy_jj_handle_executionlimit';
scriptTask_file.submit();
//schedule the MR script that uncheck the Executed checkbox in customer record
scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_jj_uncheckexecuted_btn2043';
scriptTask.deploymentId = 'customdeploy_jj_uncheckexecuted_btn2043';
scriptTaskId = scriptTask.submit();
}
}catch (e) {
log.debug("Error@summarize",e)
}
}
return {getInputData, reduce, summarize}
});