Add recipients when email send using Email button in Invoice record

Requirement:

Add recipients when email send using Email button in Invoice record

On hitting the Email button in the Invoice, autofill up to 4 contacts with a specific role under the Customer in the Invoice record in the “To” field of the email.

Solution:

The script was created for the message record (user event). The script will add up to 4 contacts with a specific role under the Customer in the Invoice record in the “To” field of the email. The script will update the contacts at before load. 

The automatic contact update was working only for invoice transactions only. 

The script was deployed for the “Create” event and “User Interface” context. 

The following sublist was available only on before load create context

Additional recipients sublist id: ‘otherrecipientslist’

Additional recipients column id: ‘otherrecipient’

Email column id: ’email’

To column id: ‘toRecipients’

CC column id: ‘cc’

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
/*******************************************************************************
 * ** Add recipients when email send using Email button in Invoice record
 * **************************************************************************
 * Author: Jobin & Jismi IT Services LLP
 * Created Date: 02 Dec 2022 ** JJ0196

 ******************************************************************************/
define(['N/record','N/search'],
    /**
 * @param{record} record
 * @param{search} search
 */
    (record,search) => {
        /**
         * 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
         * @since 2015.2
         */
        const beforeLoad = (scriptContext) =>
        {
            try
            {
                let APContactRoleID = -40;      //Consultant Role internal id from Test account.

                let messageRec = scriptContext.newRecord;
                if(scriptContext.type === 'create')
                {
                    let transactionID = messageRec.getValue({fieldId:'transaction'});
                    log.debug ({title: 'transactionID', details: transactionID});
                    let transactionType = findTransactionType(transactionID);
                    if(transactionType === "invoice")
                    {
                        let customerID = messageRec.getValue({fieldId:'entity'});
                        let contactListArray = contactSearch(customerID,APContactRoleID);
                        let customerRecord = record.load({type:"customer",id:customerID});
                        let customerEmail = customerRecord.getValue({fieldId:"email"});
                        if(contactListArray.length >0)
                        {
                            if(customerEmail)
                            {
                                let totalEmailRecipients = 4;  //Up to 4 contacts with a specific role under the Customer
                                if(contactListArray.length < totalEmailRecipients)
                                {
                                    totalEmailRecipients =contactListArray.length;
                                }
                                for(let i = 0; i < totalEmailRecipients; i++)
                                {
                                    let recipientEmail = contactListArray[i].email;
                                    let contactID = contactListArray[i].id;
                                    //log.debug ({title: 'recipientEmail', details: recipientEmail});
                                    //log.debug ({title: 'contactID', details: contactID});
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'otherrecipient',line:i, value: contactID});
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'email',line:i, value: recipientEmail});
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'toRecipients',line:i, value: true});
                                }
                            }
                            else
                            {
                                let recipientEmail = contactListArray[0].email;
                                let contactID = contactListArray[0].id;
                               
                                messageRec.setValue({fieldId: 'recipient', value: contactID});
                                messageRec.setValue({fieldId: 'recipientemail', value: recipientEmail});

                                let totalEmailRecipients = 4;  //Up to 4 contacts with a specific role under the Customer
                                if(contactListArray.length < totalEmailRecipients)
                                {
                                    totalEmailRecipients =contactListArray.length;
                                }
                                for(let i = 1; i < totalEmailRecipients; i++)
                                {
                                    recipientEmail = contactListArray[i].email;
                                    contactID = contactListArray[i].id;
                                  
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'otherrecipient',line:i-1, value: contactID});
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'email',line:i-1, value: recipientEmail});
                                    messageRec.setSublistValue({sublistId:'otherrecipientslist',fieldId: 'toRecipients',line:i-1, value: true});
                                }
                            }

                        }
                    }
                }
            }
            catch (e)
            {
                log.error ({title: 'error in beforeLoad', details: e});
            }
        }

        /**********************************************************************
         * Find Transaction type using transaction id
         * @param transactionID
         * @returns {string}
         **********************************************************************/
        function findTransactionType(transactionID)
        {
            try
            {
                let transactionSearchObj = search.create({
                    type: "transaction",
                    filters:
                        [
                            ["internalid","anyof",transactionID],
                            "AND",
                            ["mainline","is","T"]
                        ],
                    columns:
                        [
                            search.createColumn({name: "type", label: "Type"})
                        ]
                }).run().getRange({start: 0, end: 2});
                return transactionSearchObj[0].recordType;
            }
            catch (e)
            {
                log.error ({title: 'error in findTransactionType ', details: e});
            }
        }

        /**********************************************************************
         * Getting contacts list from customer record with particular role id
         * @param customerID
         * @param contactRoleID
         * @returns {*[]}
         **********************************************************************/
        function contactSearch(customerID,contactRoleID)
        {
            try
            {
                let contactListArray = [];
                let customerSearchObj = search.create({
                    type: "customer",
                    filters:
                        [
                            ["internalid","anyof",customerID],
                            "AND",
                            ["contact.role","anyof",contactRoleID],
                            "AND",
                            ["contact.isinactive","is","F"],
                            "AND",
                            ["contact.email","isnotempty",""]
                        ],
                    columns:
                        [
                            search.createColumn({name: "email", join: "contact", label: "Email"}),
                            search.createColumn({name: "internalid", join: "contact",sort: search.Sort.ASC, label: "Internal ID"}),
                            search.createColumn({name: "entityid", join: "contact", label: "Name"})
                        ]
                });
                customerSearchObj.run().each(function(result)
                {
                    let contactListObj = {};
                    let contactID = result.getValue(customerSearchObj.columns[1]);
                    let contactEmail = result.getValue(customerSearchObj.columns[0]);
                    let contactName = result.getValue(customerSearchObj.columns[2]);

                    contactListObj.id = contactID;
                    contactListObj.email = contactEmail;
                    contactListObj.name = contactName;

                    contactListArray.push(contactListObj);
                    return true;
                });
                return contactListArray;
            }
            catch (e)
            {
                log.error ({title: 'error in contactSearch ', details: e});
            }
        }

        return {beforeLoad}
    });

Leave a comment

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