Client Creation via Rest API

/**
* @NApiVersion 2.1
* @NScriptType Restlet
*/

/************************************************************************************************
BLL - 243 Client creation via REST API
*********************************************************************************************
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 25-March-2022
*
* Description : Client creation via REST API
*
* REVISION HISTORY
*
***********************************************************************************************/
define(['N/error', 'N/record', 'N/search','N/email','N/task'],
/**
* @param{error} error
* @param{record} record
* @param{search} search
*/
(error, record, search,email,task) => {

/**
* Defines the function that is executed when a POST request is sent to a RESTlet.
* @param {string | Object} requestBody - The HTTP request body; request body is passed as a string when request
* Content-Type is 'text/plain' or parsed into an Object when request Content-Type is 'application/json' (in which case
* the body must be a valid JSON)
* @returns {string | Object} HTTP response body; returns a string when request Content-Type is 'text/plain'; returns an
* Object when request Content-Type is 'application/json' or 'application/xml'
* @since 2015.2
*/


/**
Function to Create Client using Request Body
*/

function createCustomerUsingRequest(requestBody) {
try {
let message;
let custRecord = record.create({

type: record.Type.CUSTOMER,
isDynamic: true
});
if (requestBody.companyName !== '' && requestBody.companyName !== null && requestBody.companyName !== undefined) {
custRecord.setValue({
fieldId: "companyname",
value: requestBody.companyName
});
}
/**
For setting customer type
*/

if (requestBody.customerType == 'Business')
custRecord.setValue({
fieldId: "custentity_customertype",
value: 3
});
else if (requestBody.customerType == 'Charity')
custRecord.setValue({
fieldId: "custentity_customertype",
value: 2
});

if (requestBody.email !== '' && requestBody.email !== null && requestBody.email !== undefined) {
custRecord.setValue({
fieldId: "email",
value: requestBody.email
});
}

custRecord.setValue({
fieldId: "subsidiary",
value: 2
});

var postal =requestBody.address.postCode
log.debug("postal",postal)
/**
Search for finding the location using the PostCode in the Request body
*/
var customrecord_routepostcodesSearchObj = search.create({
type: "customrecord_routepostcodes",
filters:
[
["name","is",postal],
"AND",
["custrecord_route.custrecord_routelocation","noneof","@NONE@"]
],
columns:
[
search.createColumn({
name: "name",
sort: search.Sort.ASC,
label: "Name"
}),
search.createColumn({
name: "custrecord_routelocation",
join: "CUSTRECORD_ROUTE",
label: "Location"
}),
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "custrecord_route", label: "Route"})
]
});
var routeLocation;
var locSearchData = customrecord_routepostcodesSearchObj.run().getRange({
start: 0,
end: 100
});
if(locSearchData.length > 0){

for (var i = 0; i < locSearchData.length; i++) {

routeLocation =locSearchData[0].getValue({
name: "custrecord_routelocation",
join: "CUSTRECORD_ROUTE",
label: "Location"

})
}
log.debug('locID', routeLocation)

custRecord.setValue({
fieldId: "custentity_custlocation",
value: routeLocation
});
}
else
{
var postal = requestBody.address.postCode
var postalLength = postal.length ;
var postalLengthHalf = postalLength / 2 ;
var newPostCode = postal.substr(0,postalLengthHalf)
/**
Search for finding the location using the Half of the PostCode in the Request body
*/
var halfSearch= search.create({
type: "customrecord_routepostcodes",
filters:
[
["name","startswith",newPostCode],
"AND",
["custrecord_route.custrecord_routelocation","noneof","@NONE@"]
],
columns:
[
search.createColumn({
name: "name",
sort: search.Sort.ASC,
label: "Name"
}),
search.createColumn({
name: "custrecord_routelocation",
join: "CUSTRECORD_ROUTE",
label: "Location"
}),
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "custrecord_route", label: "Route"})
]
});

var routeLocation;
var locSearchData = halfSearch.run().getRange({
start: 0,
end: 100
});
if(locSearchData.length > 0){

for (var i = 0; i < locSearchData.length; i++) {

routeLocation =locSearchData[0].getValue({
name: "custrecord_routelocation",
join: "CUSTRECORD_ROUTE",
label: "Location"

})
}
log.debug('locID', routeLocation)

custRecord.setValue({
fieldId: "custentity_custlocation",
value: routeLocation
});
}

/**
Setting the value of Location as Southwater Depot if there is no PostCode Match
*/
else
{
custRecord.setValue({
fieldId: "custentity_custlocation",
value: 1
});
}

}
/**
Mapping the customer address to address subrecord
*/

custRecord.selectNewLine({
sublistId: "addressbook"
});

custRecord.setCurrentSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultshipping',
value: true,
ignoreFieldChange: true
});
// custRecord.setCurrentSublistValue('defaultshipping', requestBody.defaultShippingAddress)
custRecord.setCurrentSublistValue({
sublistId: 'addressbook',
fieldId: 'defaultbilling',
value: true,
ignoreFieldChange: true
});


var addressSubrecord = custRecord.getCurrentSublistSubrecord({
sublistId: "addressbook",
fieldId: "addressbookaddress"
});

addressSubrecord.setValue({
fieldId: "addressee",
value: requestBody.companyName
});


addressSubrecord.setValue({
fieldId: "addr1",
value: requestBody.address.address1
});

addressSubrecord.setValue({
fieldId: "city",
value: requestBody.address.city
});


addressSubrecord.setValue({
fieldId: "country",
value: requestBody.address.country

});

addressSubrecord.setValue({
fieldId: "zip",
value: requestBody.address.postCode

});

custRecord.commitLine({
sublistId: 'addressbook'
});
custRecord.setValue({
fieldId: "shippingitem",
value: 24
});
if (requestBody.tier !== null && requestBody.tier !== undefined && requestBody.tier !== "") {
if (requestBody.tier === 'Tier 1') {
custRecord.setValue({
fieldId: "territory",
value: 24
});
} else if (requestBody.tier === 'Tier 2') {
custRecord.setValue({
fieldId: "territory",
value: 25
});

} else if (requestBody.tier === 'Tier 3') {
custRecord.setValue({
fieldId: "territory",
value: 26
});

} else if (requestBody.tier === 'R.O.W') {
custRecord.setValue({
fieldId: "territory",
value: 19
});
} else if (requestBody.tier === 'Ireland') {
custRecord.setValue({
fieldId: "territory",
value: 22
});
} else if (requestBody.tier === 'Canada') {
custRecord.setValue({
fieldId: "territory",
value: 13
});
} else if (requestBody.tier === 'Australia') {
custRecord.setValue({
fieldId: "territory",
value: 23
});
}
} else {
message = displayErrorMsg('Tier is mandatory',requestBody)
return message;
}
custRecord.setValue({
fieldId: "custentity_region",
value: 4
});
custRecord.setValue({
fieldId: "custentity_supportlevel",
value: 20
});
custRecord.setValue({
fieldId: "custentity_groupaccountmanager",
value: 59485,
ignoreFieldChange:true
});
custRecord.setValue({
fieldId: "custentity_internalaccountmanager",
value: 59485

});
custRecord.setValue({
fieldId: "custentity_internalaccountmanagerstatus",
value: 59485
});

custRecord.setValue({
fieldId: "custentity_client_crm_account",
value: 1
});

custRecord.setValue({
fieldId: "leadsource",
value: -6
});
custRecord.setValue({
fieldId: "terms",
value: 4
});
// let crevalue = 1
// custRecord.setText({
// fieldId: "creditlimit",
// text: "0"
// });

/**
Search for finding the employees that belongs to the Sales Team
*/
var entitygroupSearchObj = search.create({
type: "entitygroup",
filters:
[
["internalid","anyof","60603"]
],
columns:
[

search.createColumn({
name: "internalid",
join: "groupMember",
label: "Internal ID"
})
]
});
let empID;
var searchResultCount = entitygroupSearchObj.runPaged().count;
log.debug("entitygroupSearchObj result count",searchResultCount);
entitygroupSearchObj.run().each(function(result){
// .run().each has a limit of 4,000 results
empID=result.getValue({
name: "internalid",
join: "groupMember",
label: "Internal ID"
})
log.debug("emp id",empID);

custRecord.selectNewLine({
sublistId: "salesteam"
});
custRecord.setCurrentSublistValue({
sublistId: 'salesteam',
fieldId: 'employee',
value: empID,
ignoreFieldChange: false
});
custRecord.commitLine({
sublistId: "salesteam"
});

return true;
});


custRecord.setValue({
fieldId: "currency",
value: 1
});
custRecord.setValue({
fieldId: "custentity_invoicefrequency",
value: 1
});
custRecord.setValue({
fieldId: "custentity_statement_not_required",
value: 2
});
custRecord.setValue({
fieldId: "custentity_invoiceformat",
value: 2
});
custRecord.setValue({
fieldId: "custentity_cashsaleformat",
value: 1
});
custRecord.setValue({
fieldId: "custentity_salesorderformat",
value: 16
});
custRecord.setValue({
fieldId: "custentity_statementtemplate",
value: 105
});

var custRecordId = custRecord.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
log.debug("custRecordId", custRecordId)

var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
/**
For Triggering the Map Reduce Script
*/
scriptTask.scriptId = 'customscript_custtransmapreduce';
scriptTask.deploymentId = 'customdeploy_customer_transmission_manua';
var scriptTaskId = scriptTask.submit();


return JSON.stringify({
statusCode: "SUCCESS",
message: custRecordId

});

} catch (e) {
log.debug("Error@createCustomerUsingReqest", e)
}
}
/**
Function for displaying Error Message
*/
function displayErrorMsg(errorMsg,requestBody) {
try {
let logData = customErrorLogRecord(errorMsg,requestBody)
return JSON.stringify({

statusCode: "FAILURE",
Error: errorMsg+' '+logData

})
} catch (e) {
log.debug("Error@displayErrorMsg", e)
}
}

/**
Function for Checking whether the company name already exists
*/
function existingCompanyName(requestBody){
try {

// const errorMessages = {
//
// ER004: "Company Name is already Existing",
//
// }
// let errorResponse = {
// statusCode: "Failure"
// }
if (requestBody.companyName === '' || requestBody.companyName === null || requestBody.companyName === undefined) {
let message = displayErrorMsg('CompanyName is mandatory',requestBody)
return message;
}
var customerSearchObj = search.create({
type: "customer",
filters:
[
["companyname", "is", requestBody.companyName]
// "AND",
// ["email","is",requestBody.email]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "altname", label: "Name"})

]
});
var companyName;
var searchResultCount = customerSearchObj.runPaged().count;

if (searchResultCount >0) {
customerSearchObj.run().each(function (result) {

// email= result.getValue({name: "email", label: "Email"});
companyName = result.getValue({name: "altname", label: "Name"})

// if (companyName == requestBody.companyName) {
// errorResponse.error = errorMessages.ER004;
// // return errorResponse;
// }

// return true;
});
let message=displayErrorMsg('Already existing Company Name',requestBody);
return message;

}
else
return false;



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

/**
Function for Checking whether the email already exists
*/
function existCustomerEmail(requestBody){
try {

if (requestBody.email === '' || requestBody.email === null || requestBody.email === undefined) {
let message = displayErrorMsg('Email is mandatory',requestBody)
return message;
}
//check if the customer already exists
var customerSearchObj = search.create({
type: "customer",
filters:
[
["email", "is", requestBody.email]
],
columns:
[
search.createColumn({name: "email", label: "Email"})
]
});
var email;
var searchResultCount = customerSearchObj.runPaged().count;

if (searchResultCount >0) {
customerSearchObj.run().each(function (result) {
email = result.getValue({name: "email", label: "Email"});

});
let message=displayErrorMsg('Already existing Email',requestBody);
return message;
}
else
return false;

} catch (err) {

log.debug("Error @validateCustData", err);
}
}


/**
Function for adding the errors to the custom record
*/
function customErrorLogRecord(errorMsg, requestBody) {
try {
var customLogErrorRecord = record.create({
type: "customrecord_jj_errorlogs",
isDynamic: true,
});
log.debug("customLogErrorRecord",customLogErrorRecord)
customLogErrorRecord.setValue({
fieldId: "custrecordrequest",
value: requestBody
});
customLogErrorRecord.setValue({
fieldId: "custrecorderror",
value: errorMsg
});


var recordId = customLogErrorRecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
log.debug("recordId",recordId)

/**
Sending Email to the Administrator when error response occurs
*/
let output="https://4973136-sb2.app.netsuite.com/app/common/custom/custrecordentry.nl?rectype=788&id="+recordId
let url="<a href='"+output+"'> Click Here</a>";
email.send({
author: -5,
recipients: -5,
subject: 'An error custom record is created',
body: 'Hi,'+"<br>"+'New error custom record created in netsuite'+"<br>"+
url+"&nbsp;"+'to open the record'

});

return recordId;

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

const post = (requestBody) => {

try{
log.debug("requestBody",requestBody)
let existing=existingCompanyName(requestBody);
if(existing!==false){
return existing;
};
let email=existCustomerEmail(requestBody)
if(email!==false){
return email;
};
let cust=createCustomerUsingRequest(requestBody)
return cust
}
catch(err)
{
log.debug("error@post",err)
}
}

return { post}

});

Leave a comment

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