User Event Script for adding button in Sales Order based on certain condition.
(record, search, serverWidget, url) => {
/**
* Defines the function to create a search for purchase orders based on an array of internal IDs.
* @param {Array} createPOArray – Array of internal IDs of purchase orders
* @returns {Array} – Array containing objects with finishDate and item details
*/
const createPurchaseOrderSearch = (createPOArray) => {
try {
let searchObject = [];
var purchaseorderSearchObj = search.create({
type: “purchaseorder”,
filters: [
[“type”, “anyof”, “PurchOrd”],
“AND”,
[“internalid”, “anyof”, createPOArray],
“AND”,
[“mainline”, “is”, “F”],
“AND”,
[“taxline”, “is”, “F”],
“AND”,
[“shipping”, “is”, “F”]
],
columns: [
search.createColumn({ name: “custcol_jj_ee_finish_date”, label: “Finish Date” }),
search.createColumn({ name: “item”, label: “Item” })
]
});
purchaseorderSearchObj.run().each(function (result) {
let finishDate = result.getValue({
name: “custcol_jj_ee_finish_date”, label: “Finish Date”
});
let item = result.getText({
name: “item”, label: “Item”
});
searchObject.push({ finishDate: finishDate, item: item });
return true;
});
return searchObject;
} catch (error) {
log.error(“Error in createPurchaseOrderSearch function:”, error);
return [];
}
};
/**
* Defines the function definition that is executed before record is loaded.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord – New record
* @param {string} scriptContext.type – Trigger type; use values from the context.UserEventType enum
* @param {Form} scriptContext.form – Current form
* @param {ServletRequest} scriptContext.request – HTTP request information sent from the browser for a client action only.
* @since 2015.2
*/
const beforeLoad = (scriptContext) => {
try {
if (scriptContext.type == scriptContext.UserEventType.VIEW) {
scriptContext.form.clientScriptModulePath = ‘SuiteScripts/Jobin and Jismi/Sending Confirmation Email MYNE-559/jj_cs_send_email_SO_myne559.js’
let createPoId;
let salesOrderRecord = scriptContext.newRecord;
let SOId = salesOrderRecord.getValue({ fieldId: ‘id’ });
let orderNumber = salesOrderRecord.getText({ fieldId: ‘tranid’ });
//Get the line count of the links sublist. Links sublist contains dropship and special order item object.
let lineCount = salesOrderRecord.getLineCount({ sublistId: ‘links’ });
createPOArray = [];
for (let line = 0; line < lineCount; line++) {
createPoId = salesOrderRecord.getSublistValue({
sublistId: ‘links’,
fieldId: ‘id’,
line: line
});
createPOArray.push(createPoId)
}
let searchObject = createPurchaseOrderSearch(createPOArray);
// Stringify the searchObject array
let searchObjectString = JSON.stringify(searchObject);
let finishDateExists = false;
searchObject.forEach(function (obj) {
// Check if finishDate property contains a value
if (obj.finishDate !== “”) {
finishDateExists = true;
// Exit the loop early as we only need to find one non-empty finishDate
return false;
}
});
if (finishDateExists) {
// Add button if finishDate contains a value
var form = scriptContext.form;
form.addButton({
id: ‘custpage_send_email’,
label: ‘Update Customer with ETA’,
functionName: ‘sendEmailWithParams(‘ + SOId + ‘, “‘ + orderNumber + ‘”)’
});
}
}
} catch (error) {
log.error(“Error @ beforeLoad”, error)
}
}
return { beforeLoad }
});
Client script: Suitelet is called from client script also alert is showing from client script.
function (currentRecord, url, https, runtime) {
/**
* Shows alert message.
* @param {string} message – Alert message
*/
function sendEmailWithParams(SOId, orderNumber) {
try {
let rec = currentRecord.get();
let get_url = url.resolveScript({
scriptId: ‘customscript_jj_sl_send_email_so_myne559’, //script ID
deploymentId: ‘customdeploy_jj_sl_send_email_so_myne559’, //deployment ID
returnExternalUrl: false,
params: {
salesorderId: SOId,
orderNumberSO: orderNumber,
}
});
let response = https.post
.promise({
url: get_url,
headers: {
“Content-Type”: “application/json”,
}
})
.then(function (response) {
let responseResult = JSON.parse(response.body);
console.log(“responseResult”, responseResult);
console.log(“status”, responseResult.status)
console.log(“length”, responseResult.data.length)
if (responseResult.status == true && responseResult.data.length == 0) {
alert(“Email Sent Successfully.”);
location.reload();
}
else {
console.log(“ELSE”)
alert(“Failed to send email.”);
location.reload();
}
});
}
catch (e) {
console.log({ title: “error@sendEmailWithParams”, details: e });
}
}
/**
* Function to be executed after page is initialized.
*
* @param {Object} scriptContext
* @param {Record} scriptContext.currentRecord – Current form record
* @param {string} scriptContext.mode – The mode in which the record is being accessed (create, copy, or edit)
*
* @since 2015.2
*/
function pageInit(scriptContext) {
let rec = currentRecord.get();
}
return {
sendEmailWithParams: sendEmailWithParams,
pageInit: pageInit
};
});
Send confirmation Email to customer using Suitelet.
(record, render, runtime, file, email, search, url) => {
/**
* Defines the Suitelet script trigger point.
* @param {Object} scriptContext
* @param {ServerRequest} scriptContext.request – Incoming request
* @param {ServerResponse} scriptContext.response – Suitelet response
* @since 2015.2
*/
const onRequest = (scriptContext) => {
try {
if (scriptContext.request.method === ‘POST’) {
let SOId = scriptContext.request.parameters.salesorderId;
let orderNumber = scriptContext.request.parameters.orderNumberSO;
if (SOId) {
let salesOrderRecord = record.load({
type: record.Type.SALES_ORDER,
id: SOId
});
sendEmail(SOId, salesOrderRecord, scriptContext, orderNumber);
}
}
} catch (error) {
log.error(“Error @ onRequest function”, error);
}
}
/**
* Sends confirmation email based on the sales order details.
* @param {number} SOId – Sales Order ID
* @param {Record} salesOrderRecord – Sales Order record object
* @param {Object} scriptContext – Script context object
* @param {Array} searchObject – Array containing objects with finishDate and item details
*/
function sendEmail(SOId, salesOrderRecord, scriptContext, orderNumber) {
let failedEmails = []; // Array to SOId for which email fails
let successfulEmails = []; // Array to store SOId for successful emails
try {
let recipientId = salesOrderRecord.getValue({
fieldId: ‘entity’
});
let emailField = search.lookupFields({
type: search.Type.CUSTOMER, // Assuming the customer is a Customer type record
id: recipientId,
columns: [“email”, “companyname”]
});
let emailId = emailField.email;
let customerName = emailField.companyname;
let senderId = 8780;
let subject = ‘Update on ETA for Your Order ‘ + orderNumber;
// Construct the email body
let salutation = “Dear “ + customerName + “,nn“;
let body = “Based on the current status, we anticipate that your order will be delivered to you by [ETA date]. Please note that this ETA is subject to potential minor variations due to unforeseen circumstances, but rest assured, we are doing everything in our power to ensure a timely delivery.nn“;
body += “We understand the importance of receiving your order promptly and appreciate your patience and understanding in this matter. If you have any questions about your order, please don’t hesitate to contact us by replying to this email.nn“;
let closing = “Thank you for your business!nnBest regards,”;
// Concatenate salutation, body, and closing
let emailBody = salutation + body + closing;
try {
email.send({
author: senderId,
recipients: emailId,
subject: subject,
body: emailBody,
relatedRecords: {
entityId: recipientId,
recordType: record.Type.CUSTOMER
}
});
successfulEmails.push(SOId); // Add the SOId to the successfulEmails array
} catch (e) {
log.error({ title: “Email Sending Error”, details: e });
failedEmails.push(SOId); // Add the SOId to the failedEmails array
}
// After sending all emails, check if any emails failed and provide appropriate response
scriptContext.response.write(JSON.stringify({ ‘status’: true, ‘data’: failedEmails, ‘message’: ‘sucessufully excecuted’ }));
} catch (error) {
scriptContext.response.write(JSON.stringify({ ‘status’: false, ‘data’: failedEmails, ‘message’: error.message }));
}
}
return { onRequest }
});