/**
* @NApiVersion 2.1
* @NScriptType Restlet
*/
/************************************************************************************************
BLL - 244 Contact creation via REST API
*********************************************************************************************
*
* Author: Jobin & Jismi IT Services LLP
*
* Date Created : 25-March-2022
*
* Description : Contact creation via REST API
*
* REVISION HISTORY
*
***********************************************************************************************/
define(['N/email', 'N/error', 'N/record', 'N/search','N/task'],
/**
* @param{email} email
* @param{error} error
* @param{record} record
* @param{search} search
*/
(email, error, record, search,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 display Error messages
*/
function displayErrorMsg(errorMsg,requestBody) {
try {
let logData = customErrorLogRecord(errorMsg,requestBody)
return JSON.stringify({
summary: {
message: "FAILURE",
reason: errorMsg+' '+logData
},
})
} catch (e) {
log.debug("Error@displayErrorMsg", e)
}
}
/**
Function to Create Contact using request body
*/
function createContactUsingRequest(requestBody) {
try{
let message;
let contactRecord = record.create({
type: record.Type.CONTACT,
isDynamic: true
});
var customerSearchObj = search.create({
type: "customer",
filters:
[
["companyname","is",requestBody.companyName]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "companyname", label: "Company Name"})
]
});
var customerId
var searchResultCount = customerSearchObj.runPaged().count;
log.debug("customerSearchObj result count",searchResultCount);
customerSearchObj.run().each(function(result){
customerId = result.getValue({
name: "internalid",
label: "Internal ID"
})
log.debug("customerId",customerId)
return true;
});
contactRecord.setValue({
fieldId: "company",
value: customerId
});
if (requestBody.contactName !== '' && requestBody.contactName !== null && requestBody.contactName !== undefined) {
log.debug("requestBody.contactName", requestBody.contactName);
contactRecord.setValue({
fieldId: "entityid",
value: requestBody.contactName
});
}
else {
message = displayErrorMsg('Contact Name is mandatory',requestBody)
return message;
}
if (requestBody.contactEmail !== '' && requestBody.contactEmail !== null && requestBody.contactEmail !== undefined) {
contactRecord.setValue({
fieldId: "email",
value: requestBody.contactEmail
});
}
else {
message = displayErrorMsg('Contact Email is mandatory',requestBody)
return message;
}
contactRecord.setValue({
fieldId: "subsidiary",
value: 2
});
if (requestBody.contactPhoneNumber !== '' && requestBody.contactPhoneNumber !== null && requestBody.contactPhoneNumber !== undefined) {
var checkPhone = checkPhoneNumber(requestBody)
if(checkPhone !== true){
return checkPhone
}
contactRecord.setValue({
fieldId: "phone",
value: requestBody.contactPhoneNumber
});
}
else {
message = displayErrorMsg('Contact Phone number is mandatory',requestBody)
return message;
}
if(requestBody.jobTitle !=='' && requestBody.jobTitle !== null && requestBody.jobTitle !==undefined){
contactRecord.setValue({
fieldId: "custentity3",
value: 1
});
}
else{
message = displayErrorMsg('Job Title is mandatory',requestBody)
return message;
}
log.debug("rolee",requestBody.role)
if(requestBody.role !=='' && requestBody.role !== null && requestBody.role !==undefined) {
let roleValue = 1
if(customerId!==''){
var contactSearchObj = search.create({
type: "contact",
filters:
[
["company","anyof",customerId],
"AND",
["custentity2","anyof","1"]
],
columns:
[
search.createColumn({
name: "entityid",
sort: search.Sort.ASC,
label: "Name"
}),
search.createColumn({name: "custentity2", label: "Role V2"})
]
});
var searchResultCount = contactSearchObj.runPaged().count;
log.debug("contactSearchObj result count",searchResultCount);
if(searchResultCount > 0){
roleValue =2
}
contactSearchObj.run().each(function(result){
// .run().each has a limit of 4,000 results
return true;
});
}
contactRecord.setValue({
fieldId: "custentity2",
value: roleValue
});
}
else
{
message = displayErrorMsg('Role is mandatory',requestBody)
return message;
}
var contactRecordId = contactRecord.save();
log.debug("custRecordId", contactRecordId)
/**
For triggering the Map Reduce Script
*/
var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_contacttransmission';
scriptTask.deploymentId = 'customdeploy_contacts_manual';
var scriptTaskId = scriptTask.submit();
return JSON.stringify({
statusCode: "SUCCESS",
message: contactRecordId
});
}
catch(err){
log.debug("error@createContactUsingRequest",err)
}
}
/**
Function for Phone number Validation
*/
function checkPhoneNumber(requestBody)
{
var phone=requestBody.contactPhoneNumber
log.debug("phone number inside check function",phone)
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(phone.match(phoneno))
{
return true;
}
else
{
message = displayErrorMsg(' Contact Phone number is Invalid',requestBody)
return message;
}
}
/**
Function to add the error records to 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)
/**
Function for 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+" "+'to open the record'
});
return recordId;
} catch (err) {
log.debug("error@customErrorLogRecord", err)
}
}
/**
Function to Check whether the contact is existing
*/
function existingContact(requestBody){
try{
var contactSearchObj = search.create({
type: "contact",
filters:
[
["entityid","is",requestBody.contactName]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
]
});
var searchResultCount = contactSearchObj.runPaged().count;
if(searchResultCount > 0){
let message=displayErrorMsg('Contact Name Should be Unique',requestBody);
return message;
}
else
return false;
}
catch(err){
log.debug("error@existingContact",err)
}
}
const post = (requestBody) => {
try{
log.debug("requestBody",requestBody)
let existing= existingContact(requestBody)
if(existing!==false){
return existing;
};
let contactData = createContactUsingRequest(requestBody)
return contactData
}
catch(err){
log.debug("error@Post",err)
}
}
return { post}
});