Email Capture Plugin to Approve Vendor Bill

Email Capture plugin is a NetSuite-provided plugin to capture the emails sent to a specific email ID provided by the plugin. We can use this plugin to capture the emails sent to the specific email address and based on that we can do the actions we would like to achieve, similar to approval through email, record creations through email, etc…

Email capture plugin:

function process(email) {
    try {
        // log all information in email
        var fromAddress = email.getFrom();
        nlapiLogExecution('DEBUG', 'from', fromAddress);

        var to = email.getTo();
        for (var indexTo in to) {
            nlapiLogExecution('DEBUG', 'to', to[indexTo]);
        }


        nlapiLogExecution('DEBUG', 'sent', email.getSentDate());
        nlapiLogExecution('DEBUG', 'sent date', new Date(email.getSentDate()));
        var dateSent = nlapiDateToString(new Date(email.getSentDate()), 'datetimetz')
        nlapiLogExecution('DEBUG', 'dateSent', dateSent);
        nlapiLogExecution('DEBUG', 'subject', email.getSubject());


        nlapiLogExecution('DEBUG', 'text body', email.getTextBody());


        nlapiLogExecution('DEBUG', 'html body', email.getHtmlBody());


        var attachments = email.getAttachments();
        for (var indexAtt in attachments) {
            nlapiLogExecution('DEBUG', 'att', attachments[indexAtt]);
        }
        var emailDetails = {
            from: fromAddress,
            to: to,
            sent: dateSent,
            subject: email.getSubject(),
            textbody: email.getTextBody(),
            htmlbody: email.getHtmlBody(),
            attachments: attachments
        }
        nlapiLogExecution('DEBUG', 'emailDetails', emailDetails);
        callSuitelet(emailDetails);
    } catch (e) {
        nlapiLogExecution('DEBUG', 'error@process', e);
    }
}
//Call suitelet to do the validations and approval/rejection
function callSuitelet(emailDetails) {
    try {
        nlapiLogExecution('DEBUG', 'emailDetails', emailDetails);
        var url = nlapiResolveURL('SUITELET', 'customscript_jj_sl_vendor_bill_approval_', 'customdeploy_jj_sl_vendor_bill_approval_', 'external');
        nlapiLogExecution('DEBUG', 'url', url);
        var header = [];
        header['Content-Type'] = 'application/json';
        var res = nlapiRequestURL(url, JSON.stringify(emailDetails), 'POST', 'POST');

        nlapiLogExecution('DEBUG', 'res', res);
    } catch (e) {
        nlapiLogExecution('DEBUG', 'error@callSuitelet', e);
    }
} 

Suitelet:

**
 * @NApiVersion 2.1
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/****************************************************************************
 * Macrofin- Tractable |MF-388 | [TRAC02-LG] Vendor Bill Approval via Email
 * **************************************************************************
 * Date: 16-02-2021
 * 
 * Author: Jobin & Jismi IT Services LLP
 * 
 * Description: 
 * Approve/ Reject the Vendor bill based on the email from the email capture plugin.
 * 
 * Revision  History:
 * Revision 1.0 ${16-02-2021} Gloria : created
 * 
 ******************************************************************************/
define(['N/search', 'N/record', 'N/url', 'N/email', 'N/format'],
    function (search, record, url, email, format) {//ERROR CODES
        var ERROR_EXTERNAL_USER = '1'
        var ERROR_INACTIVE_APPROVER = '2';
        var ERROR_INVALID_APPROVER = '3';
        var ERROR_WRONG_SUBJECT_FORMAT = '4';
        var ERROR_TRANS_NOT_EXIST = '5';
        var ERROR_NO_REJECT_REASON = '6';
        var ERROR_TRANS_NOT_PENDING_APPROVAL = '7';
        var ERROR_TRANS_GENERAL_ERROR = '8';
        var ERROR_TRANS_IN_PROCESS = '9';
        var ERROR_EMAIL_EXPIRED = '10'
        const NOTIFICATION_EMAIL_SENDER = 1032;
        const NOTIFY_EMAIL_RECEIVER_INVALID_USER_ATTEMPT = 1032;
        function onRequest(context) {// entry point
            //POST
            log.debug('method', context.request.method);
            if (context.request.method == 'POST') {
                try {

                    var finalObj = {}
                    var tranObj;
                    var parameters = context.request.parameters;
                    log.debug('parameters', parameters)
                    var body = JSON.parse(context.request.body);
                    log.debug('body', body)
                    var subject = body.subject;
                    log.debug('subject', subject)
                    var textbody = body.textbody
                    log.debug('textbody', textbody)
                    var from = body.from ? body.from.email : '';
                    log.debug('from', from)
                    var subjectValidate = subjectValidation(subject);
                    log.debug('subjectValidate', subjectValidate)
                    if (!isEmpty(subjectValidate)) {
                        if (!subjectValidate.valid) {
                            finalObj.errorCode = ERROR_WRONG_SUBJECT_FORMAT;
                            finalObj.errorDetails = 'Invalid subject format';
                        } else if (!isEmpty(subjectValidate) && subjectValidate.valid) {

                            tranObj = getTransaction(subjectValidate.billNumber);
                            if (!tranObj || isEmpty(tranObj)) {
                                finalObj.errorCode = ERROR_TRANS_NOT_EXIST;
                                finalObj.errorDetails = "Transaction doesn't exists";
                            } else if (tranObj.status != 1) {
                                finalObj.errorCode = ERROR_TRANS_NOT_PENDING_APPROVAL;
                                finalObj.errorDetails = "Transaction not in pending approval queue";
                            }

                        } else {
                            finalObj.errorCode = ERROR_TRANS_NOT_EXIST;
                            finalObj.errorDetails = 'Invalid transaction number';
                        }

                    } else {
                        finalObj.errorCode = ERROR_WRONG_SUBJECT_FORMAT;
                        finalObj.errorDetails = 'Invalid approver';
                    }
                    var approvedDate = body.sent;
                    log.debug("approvedDate", approvedDate)
                    var emailSendDate;
                    if (!finalObj || isEmpty(finalObj)) {
                        log.debug("in email expiry validation")

                        if (tranObj.hasOwnProperty("billStatus") && !tranObj.billStatus) {
                            emailSendDate = tranObj.level1Submitted;
                            log.debug("emailSendDate", emailSendDate)
                            var d1 = format.parse({
                                value: emailSendDate,
                                type: format.Type.DATETIME
                            });

                            var d2 = format.parse({
                                value: approvedDate,
                                type: format.Type.DATETIMETZ,
                                timezone: format.Timezone.AMERICA_LOS_ANGELES
                            });
                            log.debug("d2", d2)
                            log.debug("d1", d1)

                            var diff = d2.getTime() - d1.getTime();

                            var daydiff = diff / (1000 * 60 * 60 * 24);
                            log.debug("daydiff", daydiff)
                            if (daydiff > 1) {

                                finalObj.errorCode = ERROR_EMAIL_EXPIRED;
                                finalObj.errorDetails = 'Approval email is expired';
                            }
                        } else if (tranObj.hasOwnProperty("billStatus") && tranObj.billStatus == 1 && tranObj.status == 1) {
                            emailSendDate = tranObj.level2Submitted;
                            var d1 = format.parse({
                                value: emailSendDate,
                                type: format.Type.DATETIME
                            });

                            var d2 = format.parse({
                                value: approvedDate,
                                type: format.Type.DATETIMETZ,
                                timezone: format.Timezone.AMERICA_LOS_ANGELES
                            });
                            log.debug("d1", d1)

                            log.debug("d2", d2)
                            var diff = d2.getTime() - d1.getTime();

                            var daydiff = diff / (1000 * 60 * 60 * 24);
                            if (daydiff > 1) {
                                finalObj.errorCode = ERROR_EMAIL_EXPIRED;
                                finalObj.errorDetails = 'Approval email is expired';
                            }
                        }
                    }

                    log.debug("check final obj", isEmpty(finalObj))
                    if (!finalObj || isEmpty(finalObj)) {
                        log.debug("in approver validation")
                        if (from) {
                            var approverObj = approverValidation(from);
                            log.debug("approverObj", approverObj)
                            if (!isEmpty(approverObj)) {
                                if (approverObj.isinactive) {
                                    finalObj.errorCode = ERROR_INACTIVE_APPROVER;
                                    finalObj.errorDetails = 'inactive approver';
                                } else if (!approverObj.access) {
                                    finalObj.errorCode = ERROR_INVALID_APPROVER;
                                    finalObj.errorDetails = "invalid approver - don't have access";
                                } else if (tranObj.hasOwnProperty("billStatus") && !tranObj.billStatus) {
                                    if (!tranObj.nextApprover) {
                                        finalObj.errorCode = ERROR_INVALID_APPROVER;
                                        finalObj.errorDetails = 'no approver defined';
                                    } else if (tranObj.hasOwnProperty("nextApprover") && tranObj.nextApprover != approverObj.internalId) {
                                        finalObj.errorCode = ERROR_INVALID_APPROVER;
                                        finalObj.errorDetails = 'invalid approver';
                                    }
                                } else if (tranObj.hasOwnProperty("billStatus") && tranObj.billStatus == 1 && tranObj.status == 1) {
                                    var approvers = getApprovers();

                                    if (approvers[approverObj.internalId]) {
                                        if (approvers[approverObj.internalId].isinactive) {
                                            finalObj.errorCode = ERROR_INACTIVE_APPROVER;
                                            finalObj.errorDetails = 'inactive approver';
                                        } else if (!approvers[approverObj.internalId].access) {
                                            finalObj.errorCode = ERROR_INVALID_APPROVER;
                                            finalObj.errorDetails = "invalid approver - don't have access";
                                        }
                                    } else {
                                        finalObj.errorCode = ERROR_INVALID_APPROVER;
                                        finalObj.errorDetails = 'invalid approver';
                                    }
                                }
                            } else {
                                finalObj.errorCode = ERROR_EXTERNAL_USER;
                                finalObj.errorDetails = 'The approver is an external user';
                            }

                        }
                    }
                    log.debug("check final obj", isEmpty(finalObj))
                    if (!finalObj || isEmpty(finalObj))
                        if (subjectValidate.action == 'APPROVE') {
                            if (tranObj.hasOwnProperty("billStatus") && !tranObj.billStatus) {
                                var result = approveBill(tranObj, "level1")
                            } else if (tranObj.hasOwnProperty("billStatus") && tranObj.billStatus == 1 && tranObj.status == 1) {
                                var result = approveBill(tranObj, "level2")
                            }
                            log.debug('result', result)
                            if (result) {
                                if (result == ERROR_TRANS_IN_PROCESS) {
                                    finalObj.errorCode = ERROR_TRANS_IN_PROCESS;
                                    finalObj.errorDetails = 'in process';
                                } else {
                                    finalObj.errorCode = result;
                                    finalObj.errorDetails = result;
                                }

                            } else {
                                finalObj.errorCode = ERROR_TRANS_IN_PROCESS;
                                finalObj.errorDetails = 'not success on approve';
                            }


                        } else {
                            var reason = getRejectionReason(textbody)
                            log.debug('reject reason', reason)
                            if (reason) {
                                log.debug("login to reject")
                                var result = rejectBill(tranObj, reason)
                                log.debug('result', result)
                                if (result) {
                                    if (result == ERROR_TRANS_IN_PROCESS) {
                                        finalObj.errorCode = ERROR_TRANS_IN_PROCESS;
                                        finalObj.errorDetails = 'in process';
                                    } else {
                                        finalObj.errorCode = result;
                                        finalObj.errorDetails = result;
                                    }

                                } else {
                                    finalObj.errorCode = ERROR_TRANS_IN_PROCESS;
                                    finalObj.errorDetails = 'not success on approve';
                                }
                            } else {
                                finalObj.errorCode = ERROR_NO_REJECT_REASON;
                                finalObj.errorDetails = 'no rejection reason';
                            }


                        }

                } catch (e) {
                    log.debug("error@onRequest", e);
                    finalObj.errorCode = ERROR_TRANS_GENERAL_ERROR;
                    finalObj.errorDetails = e.message.toString();
                }
                try {
                    log.debug("finalObj", finalObj)
                    log.debug("from", from)
                    log.debug("subject", subject)
                    log.debug("tranObj", tranObj)
                    log.debug("approverObj", approverObj)
                    sendEmail(finalObj, from, subject, tranObj, approverObj)
                } catch (e) {
                    log.debug("error@emailsend", e)
                }
            }
        }


        /**
         * Marked rejected the transaction id received
         * @param {Object} tranObj - transaction details
         * @param {string} reason -reject reason
         * @returns {string}
         */
        function rejectBill(tranObj, reason) {
            try {
                log.debug('rejectBill reason', reason)
                var id = record.submitFields({
                    type: record.Type.VENDOR_BILL,
                    id: tranObj.internalId,
                    values: {
                        custbody_mf_bill_approval_status: 2,
                        custbody_mf_reject_reason: reason
                    },
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    }
                });
                log.debug('id', id)
                return 'REJECT'
            } catch (e) {
                log.debug("error@rejectBill", e)
                if (e.name == 'RCRD_HAS_BEEN_CHANGED') {

                    return ERROR_TRANS_IN_PROCESS;
                }
            }

        }


        /**
         * Get Rejection reason given the email body
         * @param {string} textbody 
         * @returns {string/ boolean}
         */
        function getRejectionReason(textbody) {
            try {
                if (textbody) {
                    var origBody = textbody.trim();
                    textbody = textbody.toLowerCase();
                    textbody = textbody.trim();
                    log.debug('textbody in reject reason', textbody)
                    var arrToken = textbody.split(/\s+/);
                    var stSubstr = null;
                    if (textbody.indexOf('reason:') >= 0 && textbody.indexOf('thanks') > 0) {

                        log.debug('origBody', origBody)
                        log.debug('textbody.indexOf Thanks', textbody.indexOf('thanks'))
                        var reason = origBody.substring(textbody.indexOf('reason:') + 7, textbody.indexOf('thanks'));
                        reason = reason.trim();
                        var arrReason = reason.split(/\s+/);
                        reason = arrReason.join(' ');
                        log.debug('reason', reason)
                        return reason;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } catch (error) {
                log.debug('error@getRejectionReason', error)
                return null;
            }
        }

        /**
         * Approve vendor bill
         * @param {Object} tranObj 
         * @param {string} approveLevel 
         * @returns {string}
         */
        function approveBill(tranObj, approveLevel) {
            try {
                if (approveLevel == "level1")
                    var values = { custbody_mf_bill_approval_status: 1 }
                else
                    var values = { custbody_mf_bill_approval_status: 3 }
                var id = record.submitFields({
                    type: record.Type.VENDOR_BILL,
                    id: tranObj.internalId,
                    values: values,
                    options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                    }
                });
                log.debug('id', id)
                return 'APPROVE'
            } catch (e) {
                log.debug("error@approveBill", e)
                if (e.name == 'RCRD_HAS_BEEN_CHANGED') {

                    return ERROR_TRANS_IN_PROCESS;
                }
            }
        }
        /**
         * Approvers for level 2 approval
         * @param null
         * @returns {object}
         */
        function getApprovers() {
            var approvers = {};
            var employeeSearchObj = search.create({
                type: "employee",
                filters:
                    [
                        ["role", "anyof", "1032"], //role -> tractable - controller

                    ],
                columns:
                    [
                        search.createColumn({ name: "altname", label: "Name" }),
                        search.createColumn({ name: "email", label: "Email" }),
                        search.createColumn({ name: "isinactive", label: "Inactive" }),
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({ name: "giveaccess", label: "Login Access" })
                    ]
            });
            var searchResultCount = employeeSearchObj.runPaged().count;
            log.debug("employeeSearchObj result count", searchResultCount);
            employeeSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                var internalId = result.getValue({ name: "internalid", label: "Internal ID" })
                var name = result.getValue({ name: "altname", label: "Name" });
                var email = result.getValue({ name: "email", label: "Email" });
                var isinactive = result.getValue({ name: "isinactive", label: "Inactive" });
                var access = result.getValue({ name: "giveaccess", label: "Login Access" })
                // if (approvers.indexOf(internalId) == -1)
                //     approvers.push(internalId)
                if (!approvers[internalId])
                    approvers[internalId] = {
                        internalId: internalId,
                        name: name,
                        email: email,
                        isinactive: isinactive,
                        access: access
                    }
                return true;
            });
            return approvers;
        }

        /**
         * Get transaction details
         * @param {sring/number} billno 
         * @returns {object}
         */
        function getTransaction(billno) {
            var tranObj = {};
            var vendorbillSearchObj = search.create({
                type: "vendorbill",
                filters:
                    [
                        ["type", "anyof", "VendBill"],
                        "AND",
                        ["transactionnumber", "is", billno],
                        "AND",
                        ["mainline", "is", "T"]
                    ],
                columns:
                    [
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({ name: "custbody_mf_level_1_approval_email", label: "Level 1 Approval Email" }),
                        search.createColumn({ name: "custbody_mf_level_2_approval_email", label: "Level 2 Approval Email" }),
                        search.createColumn({ name: "approvalstatus", label: "Approval Status" }),
                        search.createColumn({ name: "statusref", label: "Status" }),
                        search.createColumn({ name: "custbody_mf_bill_approval_status", label: "Vendor Bill Approval Status" }),
                        search.createColumn({ name: "nextapprover", label: "Next Approver" })
                    ]
            });
            var searchResultCount = vendorbillSearchObj.runPaged().count;
            log.debug("vendorbillSearchObj result count", searchResultCount);
            vendorbillSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                var internalId = result.getValue({ name: "internalid", label: "Internal ID" });
                var level1Submitted = result.getValue({ name: "custbody_mf_level_1_approval_email", label: "Level 1 Approval Email" })
                var level2Submitted = result.getValue({ name: "custbody_mf_level_2_approval_email", label: "Level 2 Approval Email" })
                var status = result.getValue({ name: "approvalstatus", label: "Approval Status" });
                var billStatus = result.getValue({ name: "custbody_mf_bill_approval_status", label: "Vendor Bill Approval Status" })
                var nextApprover = result.getValue({ name: "nextapprover", label: "Next Approver" })
                tranObj = {
                    internalId: internalId,
                    level1Submitted: level1Submitted,
                    level2Submitted: level2Submitted,
                    status: status,
                    billStatus: billStatus,
                    nextApprover: nextApprover
                }
                // return true;
            });
            return tranObj;
        }

        /**
         * validating the subject string and getting the action and the bill number
         * @param {string} subject 
         * @returns {object}
         */
        function subjectValidation(subject) {
            var subjectArr = subject.split(" ");
            var billNumber;
            var error = ''; var valid = true; var Action;
            var expectedArr = ['APPROVED:', 'VENDORBILL', 'NO.', 'XXXXX']
            if (subjectArr.length >= 4) {
                valid = ((subjectArr[0].toUpperCase() == 'APPROVED:' || subjectArr[0].toUpperCase() == 'APPROVED' || subjectArr[0].toUpperCase() == 'REJECTED:' || subjectArr[0].toUpperCase() == 'REJECTED') && subjectArr[1].toUpperCase() == 'VENDORBILL' && subjectArr[3] ? true : false);
                if (subjectArr[0].toUpperCase() == 'APPROVED:' || subjectArr[0].toUpperCase() == 'APPROVED') {
                    Action = 'APPROVE'
                } else if (subjectArr[0].toUpperCase() == 'REJECTED:' || subjectArr[0].toUpperCase() == 'REJECTED') {
                    Action = 'REJECT'
                }
                billNumber = subjectArr[3];
            } else {
                valid = false;
            }

            return { billNumber: billNumber, valid: valid, action: Action }

        }

        /**
         * getting the datails of approval email sender, including validation details
         * @param {string} from from email address in the email
         * @returns {object} 
         */
        function approverValidation(from) {
            var employeeDetails = {};
            var employeeSearchObj = search.create({
                type: "employee",
                filters:
                    [
                        ["email", "is", from]
                    ],
                columns:
                    [
                        search.createColumn({ name: "internalid", label: "Internal ID" }),
                        search.createColumn({
                            name: "entityid",
                            sort: search.Sort.ASC,
                            label: "ID"
                        }),
                        search.createColumn({ name: "altname", label: "Name" }),
                        search.createColumn({ name: "email", label: "Email" }),
                        search.createColumn({ name: "isinactive", label: "Inactive" }),
                        search.createColumn({ name: "giveaccess", label: "Login Access" })
                    ]
            });
            var searchResultCount = employeeSearchObj.runPaged().count;
            log.debug("employeeSearchObj result count", searchResultCount);
            employeeSearchObj.run().each(function (result) {
                // .run().each has a limit of 4,000 results
                var internalId = result.getValue({ name: "internalid", label: "Internal ID" });
                var name = result.getValue({ name: "altname", label: "Name" });
                var email = result.getValue({ name: "email", label: "Email" });
                var isinactive = result.getValue({ name: "isinactive", label: "Inactive" });
                var access = result.getValue({ name: "giveaccess", label: "Login Access" })
                employeeDetails = {
                    internalId: internalId,
                    name: name,
                    email: email,
                    isinactive: isinactive,
                    access: access
                }
                // return true;
            });
            return employeeDetails == {} ? false : employeeDetails;
        }

        /**
         * getting the transaction url
         * @param {string} id 
         */
        function getTransURL(id) {
            var output = url.resolveRecord({
                recordType: record.Type.VENDOR_BILL,
                recordId: id
            });
            return output;
        }

        /**
         * Send email for notification
         * @param {object} finalObj 
         * @param {string} from 
         * @param {string} subject 
         * @param {object} tranObj 
         * @param {object} approverObj 
         */
        function sendEmail(finalObj, from, subject, tranObj, approverObj) {
            log.debug(tranObj ? tranObj.internalId : 'xxx' + ':send email', 'code: ' + finalObj && finalObj != {} ? finalObj.errorCode : 'xxx' + ' details: ' + finalObj && finalObj != {} ? finalObj.errorDetails : 'xxx' + ' InternalId:' + tranObj ? tranObj.internalId : 'xxx');
            var stSubject = "";
            var stBody = "";
            var bNotifyAdminInvalid = false;
            var bNotifyAdminInactiv = false;
            var recordUrl = null;
            switch (finalObj.errorCode) {
                case ERROR_EXTERNAL_USER:
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'NON EXISTING USER';
                    bNotifyAdminInvalid = true;
                    break;
                case ERROR_EMAIL_EXPIRED:
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'EMAIL APPROVAL EXPIRED';
                    stBody = "The approval through this email is expired. Kindly approve it through clikcing the 'View Record' link given below." + "<br /><b><a href='" + recordUrl + "'>View Record<a/></b>";
                    break;
                case ERROR_WRONG_SUBJECT_FORMAT:
                    stSubject = 'INVALID SUBJECT FORMAT';
                    stBody = "The subject format must be {ACTION:} {TRANSACTION TYPE} # {TRANSACTION NUMBER}.";
                    break;
                case ERROR_TRANS_NOT_EXIST:
                    stSubject = 'TRANSACTION DOES NOT EXIST';
                    stBody = 'Kindly check the transaction number and transaction type you are approving/rejecting.';
                    break;
                case ERROR_INVALID_APPROVER:
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'INVALID ROLE/EMPLOYEE APPROVER';
                    stBody = 'You do not have permission to approve/reject this transaction.';
                    bNotifyAdminInvalid = true;
                    break;
                case ERROR_NO_REJECT_REASON:
                    stSubject = 'MISSING REJECTION REASON';
                    stBody = 'Rejection reason is required. Kindly add the reason on the email body: Example: {Reason: INVALID}.';
                    break;
                case ERROR_INACTIVE_APPROVER:
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'INACTIVE APPROVER';
                    stBody = 'You are marked inactive and do not have permission to approve/reject this transaction.';
                    bNotifyAdminInactiv = true;
                    break;
                case ERROR_TRANS_NOT_PENDING_APPROVAL:
                    stSubject = 'TRANSACTION NOT PENDING APPROVAL';
                    stBody = 'This transaction is not in pending approval queue.';
                    break;
                case ERROR_TRANS_GENERAL_ERROR:
                    stSubject = 'ERROR';
                    stBody = 'Error encountered while processing: ' + finalObj.errorDetails;
                    break;
                case ERROR_TRANS_IN_PROCESS:
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'APPROVAL IN PROGRESS';
                    stBody = 'This transaction is still in process. Please try again later.';
                    break;
                case 'APPROVE':
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'SUCCESSFULLY APPROVED';
                    stBody = 'You have successfully approved the transaction. ' + "<b><a href='" + recordUrl + "'>View Record<a/></b>";
                    break;
                case 'REJECT':
                    recordUrl = getTransURL(tranObj.internalId);
                    stSubject = 'SUCCESSFULLY REJECTED';
                    stBody = 'You have successfully rejected the transaction. ' + "<b><a href='" + recordUrl + "'>View Record<a/></b>";
                    break;
            }
            if (stSubject) {
                var stEmailSubject = stSubject + ' (' + subject + ')';
                var stEmailBody = '<p>Hi,</p>' +
                    '<p>' + stBody + '</p>' +
                    '<p>Thanks, <p/>' +
                    '<p>Admin <p/><br/>';
                var relatedRecords = {}
                relatedRecords['entityId'] = NOTIFICATION_EMAIL_SENDER;
                if (tranObj && tranObj != {} && tranObj.internalId)
                    relatedRecords['transactionId'] = tranObj.internalId;
                if (finalObj.errorCode != ERROR_EXTERNAL_USER)
                    email.send({
                        author: NOTIFICATION_EMAIL_SENDER,
                        recipients: from,
                        subject: stEmailSubject,
                        body: stEmailBody,
                        relatedRecords: relatedRecords
                    });

                if (bNotifyAdminInvalid) {
                    stSubject = 'INVALID APPROVER DETECTED';
                    stBody = "The person with an email address of '" + from + "'" + " has tried to approve/reject this <a href='" + recordUrl + "'>transaction</a>" + ' where he/she is not a valid approver.';
                    stEmailSubject = stSubject + ' (' + subject + ')';
                    stEmailBody = '<p>Hi,</p>' +
                        '<p>' + stBody + '</p>' +
                        '<p>Thanks, <p/>' +
                        '<p>Admin <p/><br/>';
                    email.send({
                        author: NOTIFICATION_EMAIL_SENDER,
                        recipients: NOTIFY_EMAIL_RECEIVER_INVALID_USER_ATTEMPT,
                        subject: stEmailSubject,
                        body: stEmailBody,
                        relatedRecords: relatedRecords
                    });

                }
                if (bNotifyAdminInactiv) {
                    stSubject = 'INACTIVE APPROVER DETECTED';
                    stBody = "The person with an email address of '" + from + "': " + '(' + approverObj.name + ')' + " has tried to approve/reject this <a href='" + recordUrl + "'>transaction</a>" + ' but he/she is marked inactive.';
                    stEmailSubject = stSubject + ' (' + subject + ')';
                    stEmailBody = '<p>Hi,</p>' +
                        '<p>' + stBody + '</p>' +
                        '<p>Thanks, <p/>' +
                        '<p>Admin <p/><br/>';
                    email.send({
                        author: NOTIFICATION_EMAIL_SENDER,
                        recipients: NOTIFY_EMAIL_RECEIVER_INVALID_USER_ATTEMPT,
                        subject: stEmailSubject,
                        body: stEmailBody,
                        relatedRecords: relatedRecords
                    });

                }
            }
        }
        function isEmpty(obj) {
            for (var key in obj) {
                if (obj.hasOwnProperty(key))
                    return false;
            }
            return true;
        }
        return {
            onRequest: onRequest
        }
    });

Leave a comment

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