Map Reduce Script TO Send Invoice Information From NetSuite To DMS Server.

Scenario:

The client needs to create a scheduled script that will fetch the invoices from the NetSuite and send them to the client’s DMS server using the DMS APIs.

/**
* @NApiVersion 2.1
* @NScriptType MapReduceScript
*/
define(['N/https', 'N/record', 'N/search'],
/**
* @param{https} https
* @param{record} record
* @param{search} search
*/
(https, record, search) => {
/**
* Defines the function that is executed at the beginning of the map/reduce process and generates the input data.
* @param {Object} inputContext
* @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {Object} inputContext.ObjectRef - Object that references the input data
* @typedef {Object} ObjectRef
* @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data
* @property {string} ObjectRef.type - Type of the record instance that contains the input data
* @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process
* @since 2015.2
*/

const getInputData = (inputContext) => {
try{

var transactionSearchObj = search.create({
type: "transaction",
filters:
[
[[["type","anyof","CustInvc"],"AND",["mainline","is","T"],"AND",["custrecord_jj_transaction_yalla_44.custrecord_jj_cutom_re_avail_yalla_44","is","F"],"AND",["custrecord_jj_transaction_yalla_44.internalid","noneof","@NONE@"]],"OR",[["type","anyof","CustInvc"],"AND",["mainline","is","T"],"AND",["custrecord_jj_transaction_yalla_44.internalid","anyof","@NONE@"]]],
"AND",
["datecreated","onorafter","15/6/2022 12:00 am"],
"AND",
["location","anyof","9"]

],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({
name: "internalid",
join: "CUSTRECORD_JJ_TRANSACTION_YALLA_44",
label: "Custom Record ID"
})
]
});
log.debug("dddd")

return transactionSearchObj

}
catch(err)
{
log.debug("error@getInputData",err)
}
}

function apiCalling(data){
let headerObj = {
"api-key": "7145f41f-c44e-4c04-866c-2811b2cbcdcb",
"Content-Type": "application/json"
}
let response = https.post({
url: 'https://yallat.mtlstaging.com/api/webhook/create-order',
body: JSON.stringify(data),
headers: headerObj
});

return response

}

function invoiceDetails(invoiceInternalId){

var invoiceSearchObj = search.create({
type: "invoice",
filters:
[
["type","anyof","CustInvc"],
"AND",
["internalid","is",invoiceInternalId],
"AND",
["mainline","is","T"]
],
columns:
[
search.createColumn({name: "entity", label: "Name"}),
search.createColumn({name: "location", label: "Location"}),
search.createColumn({name: "billaddress", label: "Billing Address"}),
search.createColumn({name: "billaddress2", label: "Billing Address 2"}),
search.createColumn({name: "billaddress1", label: "Billing Address 1"}),
search.createColumn({name: "billaddress3", label: "Billing Address 3"}),
search.createColumn({name: "billaddressee", label: "Billing Addressee"}),
search.createColumn({name: "billattention", label: "Billing Attention"}),
search.createColumn({name: "billcity", label: "Billing City"}),
search.createColumn({name: "billcountry", label: "Billing Country"}),
search.createColumn({name: "billcountrycode", label: "Billing Country Code"}),
search.createColumn({name: "billphone", label: "Billing Phone"}),
search.createColumn({name: "billingtransaction", label: "Billing Transaction"}),
search.createColumn({name: "billstate", label: "Billing State/Province"}),
search.createColumn({name: "billzip", label: "Billing Zip"}),
search.createColumn({name: "shipaddress", label: "Shipping Address"}),
search.createColumn({name: "shipaddress1", label: "Shipping Address 1"}),
search.createColumn({name: "shipaddress2", label: "Shipping Address 2"}),
search.createColumn({name: "shipaddress3", label: "Shipping Address 3"}),
search.createColumn({name: "shipaddressee", label: "Shipping Addressee"}),
search.createColumn({name: "shippingattention", label: "Shipping Attention"}),
search.createColumn({name: "shipcarrier", label: "Shipping Carrier"}),
search.createColumn({name: "shipcity", label: "Shipping City"}),
search.createColumn({name: "shippingcost", label: "Shipping Cost"}),
search.createColumn({name: "shipcountry", label: "Shipping Country"}),
search.createColumn({name: "shipcountrycode", label: "Shipping Country Code"}),
search.createColumn({name: "custcol_jj_shipping_date", label: "Shipping Date"}),
search.createColumn({name: "shippingdiscount", label: "Shipping Discount"}),
search.createColumn({name: "fxshippingdiscount", label: "Shipping Discount (Foreign Currency)"}),
search.createColumn({name: "shipname", label: "Shipping Label"}),
search.createColumn({name: "shipphone", label: "Shipping Phone"}),
search.createColumn({name: "shipstate", label: "Shipping State/Province"}),
search.createColumn({name: "shipzip", label: "Shipping Zip"}),
search.createColumn({name: "custbody_jj_latitude_joinf_42", label: "Latitude"}),
search.createColumn({name: "custbody_jj_longitude_yalla_42", label: "Longitude"})
]
});


let billShip=[]
invoiceSearchObj.run().each(function(result){
var billingAddressObj = {}
let shippingAddressObj={}
let loc={}
// .run().each has a limit of 4,000 results
billingAddressObj.name = result.getValue({
name: "billaddressee", label: "Billing Addressee"
})
billingAddressObj.address_1 = result.getValue({
name: "billaddress", label: "Billing Address"
})

billingAddressObj.address_2 = result.getValue({
name: "billaddress2", label: "Billing Address 2"
})
// var billAddressee = result.getValue({
// name: "billaddressee", label: "Billing Addressee"
// })
billingAddressObj.city = result.getValue({
name: "billcity", label: "Billing City"
})
billingAddressObj.state = result.getValue({
name: "billstate", label: "Billing State/Province"
})
billingAddressObj.country = result.getValue({
name: "billcountry", label: "Billing Country"
})
billingAddressObj.country_code = result.getValue({
name: "billcountrycode", label: "Billing Country Code"
})
billingAddressObj.phone_2 = result.getValue({
name: "billphone", label: "Billing Phone"
})

shippingAddressObj.name = result.getValue({
name: "shipaddressee", label: "Shipping Addressee"
})

shippingAddressObj.address_1 = result.getValue({
name: "shipaddress", label: "Shipping Address"
})
shippingAddressObj.address_2 = result.getValue({
name: "shipaddress1", label: "Shipping Address 1"
})
shippingAddressObj.city = result.getValue({
name: "shipcity", label: "Shipping City"
})
shippingAddressObj.state = result.getValue({

name: "shipstate", label: "Shipping State/Province"
})
shippingAddressObj.country = result.getValue({
name: "shipcountry", label: "Shipping Country"
})
shippingAddressObj.country_code = result.getValue({
name: "shipcountrycode", label: "Shipping Country Code"
})
shippingAddressObj.phone = result.getValue({
name: "shipphone", label: "Shipping Phone"
})
loc.latitude=result.getValue({
name: "custbody_jj_latitude_joinf_42", label: "Latitude"
})
loc.longitude=result.getValue({
name: "custbody_jj_longitude_yalla_42", label: "Longitude"
})

shippingAddressObj.phone_2=""
shippingAddressObj.location = loc
billShip.push(shippingAddressObj);
billShip.push(billingAddressObj)


return true;
});
return billShip
}

function itemDetails(items) {
try {
var filter = [];

filter.push(["internalid","anyof", items[0]])
for (let k = 1; k < items.length; k++) {
filter.push("OR", ["internalid","anyof", items[k]])
}


var itemSearchObj = search.create({
type: "item",
filters: filter,
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({
name: "itemid",
label: "Name"
})
]
});

let itemArray = [];

itemSearchObj.run().each(function (result) {
let obj = {}
let name = result.getValue({
name: "itemid",
label: "Name"
})

let internalID = result.getValue({
name: "internalid", label: "Internal ID"
})
// log.debug(items,internalID)
obj.item = name;
obj.internalid = internalID;
itemArray.push(obj);
return true;
});
// log.debug("Item array in search",itemArray)
return itemArray;
} catch (e) {
log.debug("error @ search", e);
}
}
function salesOrderDetails(salesOrderID){
var salesorderSearchObj = search.create({
type: "salesorder",
filters:
[
["type","anyof","SalesOrd"],
"AND",
["mainline","is","T"],
"AND",
["internalid","is",salesOrderID]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "tranid", label: "Document Number"})
]
});
let salesRef
salesorderSearchObj.run().each(function (result) {
salesRef=result.getValue({name: "tranid", label: "Document Number"});
});
return salesRef
}

function cutomRecodCreation(request,body,invoiceID,custID){
try{
let customLogErrorRecord;
if(custID && custID!==''&& custID!==null){
customLogErrorRecord=record.load({
type: "customrecord_jj_invoice_dms_yalla_44",
id: custID,
isDynamic: true
})
}
else {
customLogErrorRecord = record.create({
type: "customrecord_jj_invoice_dms_yalla_44",
isDynamic: true,
});
}

customLogErrorRecord.setValue({
fieldId: "custrecord_jj_transaction_yalla_44",
value: invoiceID
});
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_request_body_yalla_44",
value: request
});
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_response_body_yalla_44",
value: body
});
if(body["status"]==='success'){
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_cutom_re_avail_yalla_44",
value: true
});
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_error_message_yalla_44",
value: " "
});
}
else{
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_cutom_re_avail_yalla_44",
value: false
});
customLogErrorRecord.setValue({
fieldId: "custrecord_jj_error_message_yalla_44",
value: body["message"]
});

}
let recID =customLogErrorRecord.save();

return recID

}
catch (e) {
log.debug("error @ custom record creation",e)
}
}
/**
* Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered
* automatically when the associated map stage is complete. This function is applied to each group in the provided context.
* @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is
* provided automatically based on the results of the map stage.
* @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the
* reduce function on the current group
* @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group
* @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first
* invocation (if true, the current invocation is not the first invocation and this function has been restarted)
* @param {string} reduceContext.key - Key to be processed during the reduce stage
* @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage
* for processing
* @since 2015.2
*/


const reduce = (reduceContext) => {


try{
let mainObj={}
// let billingAddressObj={}

var itemCollection =[]

// var itemsObj={}
let data = reduceContext.values.map(JSON.parse)
log.debug("Data",data);
let invoiceInternalId = data[0].id
log.debug("invoiceInternalId",invoiceInternalId)
let invoiceData = record.load({
type: record.Type.INVOICE,
id: invoiceInternalId,
isDynamic: true
});

var invDate = invoiceData.getValue({
fieldId: "trandate"
})
var invoiceDate = invDate.getDate() +"/" + (invDate.getMonth()+1) +"/"+ invDate.getFullYear()
log.debug("invoiceDate",invoiceDate)
var id=invoiceData.getValue({
fieldId: 'tranid'
});

var totalAmount=invoiceData.getValue({
fieldId: 'total'
});


var salesOrderID =invoiceData.getValue({
fieldId: 'createdfrom'
});
var orderNumber = invoiceData.getValue({
fieldId:"otherrefnum"
})
var orderType = invoiceData.getText({
fieldId:"custbody15"
})
var soRef=salesOrderDetails(salesOrderID);
log.debug("SoRef",soRef);


var paymentMethod = invoiceData.getText({
fieldId: 'terms'
});
var paymentStatus = invoiceData.getValue({
fieldId: 'custbody10'
});
var shippingMethod = invoiceData.getText({
fieldId: 'shipmethod'
});


var shipDate = invoiceData.getValue({
fieldId: 'shipdate'
});

var shippingDate = shipDate.getDate() +"/" + (shipDate.getMonth()+1) +"/"+ shipDate.getFullYear()
log.debug("shipping Date",shippingDate)

var discountCoupon = invoiceData.getValue({
fieldId: 'custbody_celigo_etail_discount_code'
});

var orderDevice = invoiceData.getValue({
fieldId: 'custbody17'
});
var memo = invoiceData.getValue({
fieldId: 'memo'
});
var customerNote = invoiceData.getValue({
fieldId: 'custbody_magento_order_note'
});
// let location={}
// location.latitude=invoiceData.getValue({
// fieldId: 'custbody_jj_latitude_joinf_42'
// });
// location.longitude=invoiceData.getValue({
// fieldId: 'custbody_jj_longitude_yalla_42'
// });
var billShip=invoiceDetails(invoiceInternalId)
log.debug("Bill ship",billShip)

let sameday=invoiceData.getValue({
fieldId: 'custbody_jj_deliver_day_yalla_51'
});
let same,next
if(sameday===1 || sameday==='1'){
same=true;
next=false;
}else{
same=false;
next=true;
}
log.debug("same day",sameday);
let deliveryTeam=invoiceData.getValue({
fieldId: 'custbody_jj_deliver_team_yalla_51'
});
let inter,ext
if(deliveryTeam===1 || deliveryTeam==='1'){
inter=true
ext=false
}
else{
inter=false
ext=true
}
log.debug("Delivery team",deliveryTeam)
let lineCount = invoiceData.getLineCount({
sublistId: 'item'
});
let skuArray = [];
for (var i =0 ; i < lineCount ; i++) {
let item = invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'item',
line: i
});
skuArray[i]=item
}
let itemsArr=itemDetails(skuArray);

for(var i=0;i<lineCount;i++){
var itemsObj = {}
let item = invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'item',
line: i
});
itemsObj.item_name = invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'item_display',
line: i
});
for(var j=0;j<itemsArr.length;j++) {

if (item === itemsArr[j]["internalid"]) {
itemsObj.item_sku = itemsArr[j]["item"]
}
}
itemsObj.quantity = invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'quantity',
line: i
});
itemsObj.item_price = invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'rate',
line: i
});
let grossAmount=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'grossamt',
line: i
});
itemsObj.gross_amount=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'grossamt',
line: i
});
let afterDiscount=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'custcol_jj_amount_after_discou',
line: i
});
itemsObj.discount_amount=grossAmount-afterDiscount
itemsObj.amount_after_discount= invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'custcol_jj_amount_after_discou',
line: i
});
itemsObj.description=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'description',
line: i
});
itemsObj.item_code=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'custcol_rt_item_code',
line: i
});
itemsObj.item_image=invoiceData.getSublistValue({
sublistId: 'item',
fieldId: 'custcol_jj_item_image_yalla_42',
line: i
});
itemCollection.push(itemsObj);

}
// log.debug("Item Collection",itemCollection)
mainObj.invoice_no=id;
mainObj.invoice_date=invoiceDate;
mainObj.order_number=orderNumber;
mainObj.total_amount=totalAmount;
mainObj.order_type=orderType;
mainObj.sales_order_ref=soRef;
mainObj.payment_method=paymentMethod;
mainObj.payment_status=paymentStatus;
mainObj.shipping_method=shippingMethod;
mainObj.shipping_date=shippingDate;
mainObj.same_day_delivery=same
mainObj.next_day_delivery=next;
mainObj.is_internal_delivery=inter;
mainObj.external_delivery=ext;
mainObj.delivery_date=shippingDate
mainObj.is_cash_on_delivery=true;
mainObj.discount_coupon=discountCoupon;
mainObj.order_device=orderDevice;
mainObj.memo=memo;
mainObj.customer_order_note=customerNote;
mainObj.shipping_address=billShip[0];
mainObj.billing_address=billShip[1];
mainObj.items=itemCollection;

log.debug(" Main Obj",mainObj)


let response=apiCalling(mainObj)

log.debug("response",response);
// log.debug("response body",response.body)
let body=JSON.parse(response.body)
log.debug("Body",body)

let customRecID=data[0].values["internalid.CUSTRECORD_JJ_TRANSACTION_YALLA_44"].value
log.debug("custID",customRecID);
let custRecord=cutomRecodCreation(mainObj,body,invoiceInternalId,customRecID)

log.debug(" After Saving",custRecord)

reduceContext.write({
key: 'success',
value: custRecord
})

}

catch(err)
{
log.debug("error@Reduce",err)
let a=err
log.debug("aa",a)
let result = reduceContext.values.map(JSON.parse);
reduceContext.write({
key: 'error',
value: {...result, 'error': a}
});
}

}


const summarize = (summaryContext) => {
try {
log.debug("***In Summarize****")
summaryContext.output.iterator().each(function (key, value) {

if (key === 'error') {
let parseSummary = JSON.parse(value);
log.debug("Parse Summary", parseSummary)
}
})
}catch (e) {
log.debug("error @ summarize",e)
}
}

return {getInputData, reduce,summarize}

});

Leave a comment

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