Jira Code: ISO-32 Call Monkey API
Call Monkey is a call centre managing software. Call monkey is integrated with NetSuite using the Call monkey API. When a lead record is created in NetSuite and the save to call monkey checkbox is marked, the corresponding lead is created in call monkey using a user event script. Call monkey then sets the appointment and status for the lead. A scheduled script at NetSuite running at an interval of 15 minutes updates the appointment and status from call monkey to lead in NetSuite.
User event script to create Lead in Call Monkey
/**
* @NApiVersion 2.x
* @NScriptType UserEventScript
* @NModuleScope SameAccount
*/
define(['N/http', 'N/https', 'N/format', 'N/record', 'N/search'],
function(http, https, format, record, search) {
var myArray;
//function to search in field array
function fieldSearch(nameKey, optionKey) {
try {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].fieldId === nameKey) {
return ((myArray[i].type === "PULL_DOWN" || myArray[i].type === "CHECK_BOX") ?
optionSearch(optionKey, myArray[i].options) : myArray[i].id);
}
}
} catch (e) {
log.debug({ title: "error in fieldSearch", details: e });
}
}
function optionSearch(optionKey, myArray1) {
try {
log.debug({ title: "optionKey", details: optionKey });
log.debug({ title: "myArray1", details: myArray1 });
for (var i = 0; i < myArray1.length; i++) {
if (myArray1[i].name === optionKey) {
return myArray1[i].id;
}
}
} catch (e) {
log.debug({ title: "error in optionSearch", details: e });
}
}
function getlistval(listid, val) {
try {
var list = record.load({
type: "customlist",
id: listid
});
var optionsCount = list.getLineCount({
sublistId: 'customvalue'
});
for (i = 0; i < optionsCount; i++) {
var id = list.getSublistValue({
sublistId: 'customvalue',
fieldId: 'valueid',
line: i
})
if (id == val)
return list.getSublistValue({
sublistId: 'customvalue',
fieldId: 'value',
line: i
})
}
} catch (e) {
log.debug("error in getlistval", e);
}
}
function getemployee(id) {
try {
var employeeSearchObj = search.create({
type: "employee",
filters: [
["internalidnumber", "equalto", id]
],
columns: [
search.createColumn({
name: "entityid",
sort: search.Sort.ASC
})
]
});
var searchResultCount = employeeSearchObj.runPaged().count;
var ram;
employeeSearchObj.run().each(function(result) {
ram = result.getValue({ name: "entityid" })
});
return ram;
} catch (e) {
log.debug("e in getemployee", e);
}
}
/**
* Function definition to be triggered before record is loaded.
*
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {Record} scriptContext.oldRecord - Old record
* @param {string} scriptContext.type - Trigger type
* @Since 2015.2
*/
function afterSubmit(scriptContext) {
try {
log.debug("type",scriptContext.type);
if(scriptContext.type!='create')
return;
var rec = scriptContext.newRecord;
/**start ,select all necessary fields from netsuite**/
var savetocall = rec.getValue({
fieldId: 'custentity_jj_save_tocall_monkey'
});
log.debug({ title: "savetocall", details: savetocall });
var calladdressid = rec.getValue({
fieldId: 'custentity_jj_callmonkey_address'
});
log.debug({ title: "calladdressid", details: calladdressid });
if (savetocall && (calladdressid == null || calladdressid == "")) {
try {
var naam = rec.getText({
fieldId: 'custentityll_naam'
});
} catch (e) {
var naamval = rec.getValue({
fieldId: 'custentityll_naam'
});
var naam = getlistval(131, naamval);
}
var dateLeadGathered1 = rec.getValue({
fieldId: 'custentity8'
});
if((dateLeadGathered1!='')&&(dateLeadGathered1!=null)){
var parsedDateStringAsRawDateObject = format.parse({
value: dateLeadGathered1,
type: format.Type.DATE
});
var formattedDateString = format.format({
value: parsedDateStringAsRawDateObject,
type: format.Type.DATE
});
log.debug("formattedDateString",formattedDateString);
dateLeadGathered1=formattedDateString.split("/");
var dateLeadGathered=dateLeadGathered1[0]+"-"+dateLeadGathered1[1]+"-"+dateLeadGathered1[2];
log.debug("dateLeadGathered",dateLeadGathered);
}
var timeLeadGathered = rec.getValue({
fieldId: 'custentitytijdleadopgehaald_ilse'
});
if((timeLeadGathered!='')&&(timeLeadGathered!=null)){
timeLeadGathered = format.format({
value: timeLeadGathered,
type: format.Type.TIMEOFDAY
});
}
log.debug("timeLeadGathered",timeLeadGathered);
try {
var door2door = rec.getText({
fieldId: 'custentity6'
});
} catch (e) {
var door2doorval = rec.getValue({
fieldId: 'custentity6'
});
var door2door = getlistval(128, door2doorval);
}
try {
var region = rec.getText({
fieldId: 'custentityregio'
});
} catch (e) {
var regionval = rec.getValue({
fieldId: 'custentityregio'
});
var region = getlistval(154, regionval);
}
try {
var adviseur = rec.getText({
fieldId: 'custentityadviseur_ilse'
});
} catch (e) {
var adviseurval = rec.getValue({
fieldId: 'custentityadviseur_ilse'
});
var adviseur = getemployee(adviseurval);
}
var isperson=rec.getValue({
fieldId: 'isperson'
});
if(isperson=='T'){
var gender = rec.getValue({
fieldId: 'salutation'
});
if(gender=='Dhr.'){
gender='Heer';
}
if(gender=='Mevr.'){
gender='Mevrouw';
}
}
if(isperson=='F'){
var gender='Bedrijf'
}
log.debug("gender",gender);
log.debug("isperson",isperson);
var firstName = rec.getValue({
fieldId: 'firstname'
});
var lastname = rec.getValue({
fieldId: 'lastname'
});
var telephoneNumber = rec.getValue({
fieldId: 'phone'
});
var homeTelephoneNumber = rec.getValue({
fieldId: 'mobilephone'
});
var email = rec.getValue({
fieldId: 'email'
});
try {
var contactPreference = rec.getText({
fieldId: 'custentity7'
});
} catch (e) {
var contactPreferenceval = rec.getValue({
fieldId: 'custentity7'
});
var contactPreference = getlistval(129, contactPreferenceval);
}
if((contactPreference!="")&&(contactPreference!=null)){
var contactPreference = contactPreference.charAt(0).toUpperCase() + contactPreference.slice(1);
}
var remarksLead = rec.getValue({
fieldId: 'custentityopmerkingen_lead_ilse'
});
log.debug("remarksLead",remarksLead);
var remarksLead=extractContent(remarksLead)
remarksLead=remarksLead.replace(/ /g, '');
log.debug("remarksLead",remarksLead);
try {
var durableEnergy = rec.getText({
fieldId: 'custentityenergysource'
});
} catch (e) {
var durableEnergyval = rec.getValue({
fieldId: 'custentityenergysource'
});
var durableEnergy = getlistval(145, durableEnergyval);
}
try {
var energyPrice = rec.getText({
fieldId: 'custentityenergyprice'
});
} catch (e) {
var energyPriceval = rec.getValue({
fieldId: 'custentityenergyprice'
});
var energyPrice = getlistval(146, energyPriceval);
}
try {
var noinvest = rec.getText({
fieldId: 'custentitynoinvest'
});
} catch (e) {
var noinvestval = rec.getValue({
fieldId: 'custentitynoinvest'
});
var noinvest = getlistval(147, noinvestval);
}
try {
var energyNota = rec.getText({
fieldId: 'custentityenergynota'
});
} catch (e) {
var energyNotaval = rec.getValue({
fieldId: 'custentityenergynota'
});
var energyNota = getlistval(148, energyNotaval);
}
try {
var houseOwner = rec.getText({
fieldId: 'custentityhouseowner'
});
} catch (e) {
var houseOwnerval = rec.getValue({
fieldId: 'custentityhouseowner'
});
var houseOwner = getlistval(150, houseOwnerval);
}
try {
var finances = rec.getText({
fieldId: 'custentityfinances'
});
} catch (e) {
var financesval = rec.getValue({
fieldId: 'custentityfinances'
});
var finances = getlistval(149, financesval);
}
try {
var relationaggrement = rec.getText({
fieldId: 'custentitypartnerok'
});
} catch (e) {
var relationaggrementval = rec.getValue({
fieldId: 'custentitypartnerok'
});
var relationaggrement = getlistval(155, relationaggrementval);
}
var addressobj = findaddress(rec);
var address = addressobj.addr1;
var housenumber = address.match(/\d+/g);
if((housenumber!='')&&(housenumber!=null)&&(housenumber!=undefined)){
housenumber=housenumber[0];
}
var housenumber1 = addressobj.houseexten;
var zipcode = addressobj.zip;
var cityname = addressobj.city;
var contactForAppointment = rec.getValue({
fieldId: 'custentityakkoord_telcon_afspraak_ilse'
});
/**End ,select all necessary fields from netsuite)**/
var headerObj = { "Accept": "application/json" };
var callMonkeyResponse = https
.get({
url: 'https://backoffice.callmonkey.com/external-api/field/get-all?apiKey=8a62db93-f096-464b-947f-c750f3a91780',
headers: headerObj
});
var data = callMonkeyResponse.body;
var data1 = JSON.parse(data);
myArray = data1.data;
var genderid = fieldSearch('CPGender', gender);
log.debug("genderid",genderid);
var door2doorId = fieldSearch('DOOR2DOORCAMPAGNEREGIO', door2door);
var contactPreferenceId = fieldSearch('BESCHIKBAARHEID', contactPreference);
// log.debug("contactPreferenceId", contactPreferenceId)
var headerObj = { "Accept": "application/json", "Content-Type": "application/json", "apiKey": "8a62db93-f096-464b-947f-c750f3a91780" };
var fieldarray = [];
var regionob = { "fieldId": "WELKESTIMULERINGSREGELINGISVANTOEPASSING", "value": region };
var gender = { "fieldId": "CPGender", "optionUuids": [genderid] };
var contactpref = { "fieldId": "BESCHIKBAARHEID", "optionUuids": [contactPreferenceId] };
var lastnameobj = { "fieldId": "CPLastname", "value": lastname };
var leadmaker = { "fieldId": "LEADMAKER", "value": naam };
var door = { "fieldId": "DOOR2DOORCAMPAGNEREGIO", "optionUuids": [door2doorId] };
var advisor = { "fieldId": "ADVISEUR", "value": adviseur };
var firstnme = { "fieldId": "CPFirstname", "value": firstName };
var addr1 = { "fieldId": "ORStreet", "value": address };
var leaddate = { "fieldId": "LEADDATUM", "value": dateLeadGathered };
var leadtime = { "fieldId": "LEADTIJD", "value": timeLeadGathered };
var housnum = { "fieldId": "ORHouseNumber", "value": housenumber };
var zip = { "fieldId": "ORPostcode", "value": zipcode };
var city = { "fieldId": "ORCity", "value": cityname };
var phone = { "fieldId": "CPTelephone1", "value": telephoneNumber };
var aleternate = { "fieldId": "CPMobile", "value": homeTelephoneNumber };
var emailobj = { "fieldId": "CPEmail1", "value": email };
var content = { "fieldId": "OPMERKINGENKCC", "value": remarksLead };
var houesownrobj = { "fieldId": "ISDECONTACTPERSOONDANWELPARTNEREIGENAARVANDEWONING", "value": houseOwner };
var relationaggrementobj = { "fieldId": "ISDERELATIEAKKOORDDATERCONTACTWORDTOPGENOMENVOORHETMAKENVANEENAFSPRAAK", "value": relationaggrement };
var durableEnergyobj = { "fieldId": "WATISVOLGENSUDEMEESTDUURZAMEBRONVANENERGIE", "value": durableEnergy };
var energyPriceobj = { "fieldId": "VERWACHTINGENERGIEPRIJSENBIJKOMENDEKOSTEN", "value": energyPrice };
var noinvestIdobj = { "fieldId": "ALSUZONDERDATHETUMEERKOSTPMENZONDEREIGENINVESTERINGOVERKUNTGAANOPDUURZAMEZONNEENERGIEZOUUDATDANOVERWEGEN", "value": noinvest };
var financesdobj = { "fieldId": "BEHEERDECONTACTPERSOONZELFSTANDIGOFSAMENMETDEPARTNERHETFINANCIELEHUISHOUDEN", "value": finances };
var energyNotaobj={ "fieldId": "BEDRAAGTDEENERGIENOTAMEERDAN30EUROPMDAN1250KWH", "value": energyNota };
fieldarray.push(lastnameobj, leadmaker, regionob, advisor, firstnme, addr1, city, emailobj, content, houesownrobj, relationaggrementobj, durableEnergyobj, energyPriceobj, noinvestIdobj, financesdobj, phone, aleternate, leaddate, leadtime,zip,housnum,energyNotaobj);
if (genderid != null) {
fieldarray.push(gender);
}
if (door2doorId != null) {
fieldarray.push(door);
}
if (contactPreferenceId != null) {
fieldarray.push(contactpref);
}
log.debug({ title: "fieldarray", details: fieldarray });
var bodyObj = { "campaignId": "85e1bf6d-812c-42fc-a442-6561d20ef989", "fields": fieldarray };
var stringbody = JSON.stringify(bodyObj);
var addressResponse = https
.post({
url: 'https://backoffice.callmonkey.com/external-api/address/create?apiKey=8a62db93-f096-464b-947f-c750f3a91780',
body: stringbody,
headers: headerObj
});
log.debug("addressResponse",addressResponse);
statusCode = addressResponse.code;
log.debug("statusCode",statusCode);
var responseBody = JSON.parse(addressResponse.body);
if (statusCode == 200) {
var addressId = responseBody.id;
log.debug({ title: "addressId", details: addressId });
internalid = scriptContext.newRecord.id;
log.debug({ title: "internalid", details: internalid });
//setting the custom field Trigger type in the sales order
var id = record.submitFields({
type: record.Type.LEAD,
id: scriptContext.newRecord.id,
values: {
custentity_jj_callmonkey_address: addressId
},
options: {
enableSourcing: true,
ignoreMandatoryFields: true,
ignoreFieldChange: false
}
});
log.debug({ title: "id", details: id });
}
else{
var errorr=responseBody.errors;
if((errorr!='')&&(errorr!=null)&&(errorr!=undefined))
{
var errormsg=errorr[0].message;
log.debug("errormsg",errormsg);
if((errormsg!='')&&(errormsg!=null)&&(errormsg!=undefined))
{
record.submitFields({
type: record.Type.LEAD,
id: scriptContext.newRecord.id,
values: {
custentity_jj_callmonkey_err_msg: errormsg
},
options: {
enableSourcing: true,
ignoreMandatoryFields: true,
ignoreFieldChange: false
}
});
}
}
}
}
} catch (e) {
log.debug({
title: 'error in main',
details: e
});
}
}
return {
afterSubmit: afterSubmit
};
function extractContent(s) {
return s.replace(/<[^>]+>/g, '');
};
function findaddress(resultrec) {
try {
log.debug({ title: "resultrec.id", details: resultrec.id });
var leadSearchObj = search.create({
type: "lead",
filters: [
["stage", "anyof", "LEAD"],
"AND", ["internalidnumber", "equalto", resultrec.id]
],
columns: [
search.createColumn({
name: "custrecord_houesnumber",
join: "Address"
}),
search.createColumn({
name: "custrecord_housenumber_extension",
join: "Address"
}),
search.createColumn({
name: "city",
join: "Address"
}),
search.createColumn({
name: "zipcode",
join: "Address"
}),
search.createColumn({
name: "address1",
join: "Address"
}),
search.createColumn({
name: "statedisplayname",
join: "Address"
})
]
});
var results = leadSearchObj.run().getRange({
start: 0,
end: 1000
});
log.debug({ title: "results", details: results });
var customer = {};
if(results.length>0){
var result = results[0];
customer.zip = result.getValue({
name: "zipcode",
join: "Address"
});
customer.city = result.getValue({
name: "city",
join: "Address"
});
customer.houseexten = result.getValue({
name: "custrecord_housenumber_extension",
join: "Address"
});
customer.housenum = result.getValue({
name: "custrecord_houesnumber",
join: "Address"
});
customer.addr1 = result.getValue({
name: "address1",
join: "Address"
});
}
// log.debug({ title: "customer", details: customer });
return customer;
} catch (e) {
log.debug({ title: "e in address ", details: e });
}
}
});
Scheduled script to update appointment and status from call monkey
/**
* @NApiVersion 2.x
* @NScriptType ScheduledScript
* @NModuleScope SameAccount
*/
/**
* Script Description: This script sets lead status,appointment , salesrep etc from callmonkey to netsuite
* Scheduled in every 15 mins
*/
/***************************************************************************
* * ISOGOED * *
* *************************************************************************
* Date:23/4/18
* Script name: JJ SS IS Call Monkey Lead Status Update
* Script id: customscriptjj_ss_is_call_monkey_lead
* Applied to: Lead
*
***************************************************************************/
define(
['N/https', 'N/email', 'N/record', 'N/search', 'N/runtime', 'N/task', 'N/file', 'N/format'],
function(https, email, record, search, runtime, task, file, format) {
/**
* Definition of the Scheduled script trigger point.
*
* @param {Object}
* scriptContext
* @param {string}
* scriptContext.type - The context in which the script
* is executed. It is one of the values from the
* scriptContext.InvocationType enum.
* @Since 2015.2
*/
function execute(scriptContext) {
try {
var searchobj = createsearch();
for (var i = 0; i < searchobj.length; i++) {
var response = sendrequest(
searchobj[i].callmonkey_address,
searchobj[i].internalid);
}
} catch (e) {
log.debug({
title: "e in main",
details: e
});
}
}
return {
execute: execute
};
/* function to send request to callmonkey api to get lead details */
function sendrequest(address, internalid) {
try {
var queryurl = "https://backoffice.callmonkey.com/external-api/address/get/" +
address
var headerobj = {
accept: "application/json",
apikey: "8a62db93-f096-464b-947f-c750f3a91780"
}
var response = https.get({
url: queryurl,
headers: headerobj
});
if (response.code == 200) {
var currentstatus = formatresponse(response.body);
var response = JSON.parse(response.body);
//log.debug("response.dispositions",response.dispositions);
var appointment = searchDispositionName(response.dispositions);
if (appointment != 'no appointment') {
var updateAppointment = createAppointment(appointment);
var id = updatestatus(internalid, currentstatus,
updateAppointment);
} else {
var id = updatestatus(internalid, currentstatus,
'no appointment');
}
}
log.debug({
details: id,
title: "id"
});
} catch (e) {
log.debug("Error in sendrequest", e);
}
}
function createAppointment(appointment) {
try {
var appDetails = {};
log.debug({
title: 'appointment',
details: appointment
});
appDetails.startDateTime = convertDateTime(appointment.followUpDate);
appDetails.endDateTime = convertDateTime(appointment.followUpEndDate);
var employeeSearchObj = search.create({
type: "employee",
filters: [
["entityid", "haskeywords",
appointment.salesEmployeeName
]
],
columns: [
"internalid"
]
});
var resultSet = employeeSearchObj.run();
var firstResult = resultSet.getRange({
start: 0,
end: 1
})[0];
var emId = null;
if ((firstResult != '') && (firstResult != null) &&
(firstResult != undefined)) {
if (((firstResult.getValue({
name: 'internalid'
})) != '') && ((firstResult.getValue({
name: 'internalid'
})) != null) && ((firstResult.getValue({
name: 'internalid'
})) != undefined)) {
emId = parseFloat(firstResult.getValue({
name: 'internalid'
}));
}
}
appDetails.salesRep = emId;
return appDetails;
} catch (e) {
log.debug("Error in createAppointment", e);
}
}
/* function to convert appointment date and time to netherland timezone */
function convertDateTime(date) {
try {
//log.debug("date1",date);
var newdate = new Date(date);
var converted_date = format.format({ value: newdate, type: format.Type.DATETIME, timezone: format.Timezone.EUROPE_AMSTERDAM });
//log.debug("converted_date",converted_date);
return converted_date;
} catch (e) {
log.debug("error in convertDateTime", e);
}
}
function searchDispositionName(dispositions) {
try {
var appointment = null;
for (var i = 0; i < dispositions.length; i++) {
if (dispositions[i].name == 'Afspraak A') {
appointment = dispositions[i];
break;
} else {
appointment = 'no appointment';
}
}
return appointment;
} catch (e) {
log.debug("error in searchDispositionName", e);
}
}
/* function to get internalid and callmonkey addres of leads */
function createsearch() {
try {
var leadSearchObj = search
.create({
type: "lead",
filters: [
["stage", "anyof", "LEAD"],
"AND",
["custentity_jj_save_tocall_monkey",
"is", "T"
],
"AND",
["custentity_jj_callmonkey_address",
"isnotempty", ""
]
],
columns: [search.createColumn({
name: "entityid",
sort: search.Sort.ASC
}), "altname", "email",
"custentity_jj_save_tocall_monkey",
"custentity_jj_callmonkey_address",
"internalid", "entitystatus"
]
});
var i = 0;
var leadarray = [];
var searchResultCount = leadSearchObj.runPaged().count;
var i = 0;
leadSearchObj.run().each(function(result) {
var leadobj = {};
leadobj.internalid = result.getValue({
name: 'internalid'
});
leadobj.callmonkey_address = result.getValue({
name: 'custentity_jj_callmonkey_address'
});
leadarray.push(leadobj);
return true
});
return leadarray;
} catch (e) {
log.debug({
details: e,
title: "e in search"
});
}
}
function formatresponse(response) {
try {
/*log.debug({
details : response,
title : "response"
});*/
var response = JSON.parse(response);
var statusarray = response.dispositions;
var currentstatus = statusarray[statusarray.length - 1].type;
log.debug({
details: currentstatus,
title: "currentstatus"
});
return currentstatus;
} catch (e) {
log.debug({
details: e,
title: "e in format"
});
}
}
/* function to set status , appointment , salesrep to Lead record */
function updatestatus(internalid, status, emp) {
try {
var leadstatusobj = {
CALLBACK: "21",
QUALIFIED: "7",
NEGATIVE: "19",
DISCHARGE: "22",
CANCELLED: "23",
OPEN: "6"
};
// set appointment , status and salesrep if lead has appointment from callmonkey
if (emp != 'no appointment') {
var rec = record.load({
type: record.Type.LEAD,
id: internalid,
isDynamic: true
});
// set lead status
rec.setValue({
fieldId: 'entitystatus',
value: leadstatusobj[status]
});
//log.debug("emp.startDateTime",emp.startDateTime);
// set appointment
if ((emp.startDateTime != '') && (emp.startDateTime != null)) {
var formattedDate = format.format({
value: emp.startDateTime,
type: format.Type.DATETIME
});
var parsedDate = format.parse({
value: formattedDate,
type: format.Type.DATETIME
});
rec.setValue({
fieldId: 'custentity_jj_lead_appointment',
value: parsedDate
});
}
var count = rec.getLineCount({
sublistId: 'salesteam'
});
var employee_name;
var flag = true;
// check if salesrep from callmonkey is already set as salesrep
for (var i = 0; i < count; i++) {
employee_name = rec.getSublistValue({
sublistId: 'salesteam',
fieldId: 'employee',
line: i
});
//log.debug("employee_name",employee_name);
if (employee_name == emp.salesRep) {
flag = false;
break;
}
}
// set salesrep if salesrep from callmonkey is not already set
if (flag == true) {
var lineNum = rec.selectNewLine({
sublistId: 'salesteam'
});
rec.setCurrentSublistValue({
sublistId: 'salesteam',
fieldId: 'employee',
value: emp.salesRep,
ignoreFieldChange: false
});
rec.setCurrentSublistValue({
sublistId: 'salesteam',
fieldId: 'salesrole',
value: '-2',
ignoreFieldChange: true
});
rec.setCurrentSublistValue({
sublistId: 'salesteam',
fieldId: 'isprimary',
value: true,
ignoreFieldChange: true
});
rec.commitLine({
sublistId: 'salesteam'
});
}
// set assign to sales rep as true
rec.setValue({
fieldId: 'custentity_jj_assign_to_sales_rep',
value: true
});
var recordId = rec.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
}
// if lead has no appointment set only lead status
else {
var recordId = record.submitFields({
type: record.Type.LEAD,
id: internalid,
values: {
entitystatus: leadstatusobj[status]
},
options: {
enableSourcing: false,
ignoreMandatoryFields: true
}
});
}
return recordId
} catch (e) {
log.debug({
details: e,
title: "e in updatestatus"
});
}
}
});