Approval Process Using User Event Script

Client needs to do an approval process for a custom record.

The approval process has been completed using user event script.

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
define(['N/record', 'N/runtime', 'N/search','N/ui/serverWidget','N/error','N/config','N/email'],
    /**
 * @param{record} record
 * @param{runtime} runtime
 * @param{search} search
 */
    (record, runtime, search,serverWidget,error,config,email) => {
        /**
         * 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
         */

        function projectDetails(projectId){
            try{
                let jobSearchObj = search.create({
                    type: "job",
                    filters:
                    [
                       ["internalid","anyof",projectId]
                    ],
                    columns:
                    [
                       search.createColumn({name: "custentity_jj_prj_managers", label: "Project Owner"}),
                       search.createColumn({name: "projectmanager", label: "Project Manager"})
                    ]
                 });
                 let searchResultCount = jobSearchObj.runPaged().count;
                 let projectDetails={}
                 let managers=[]
                 log.debug("jobSearchObj result count",searchResultCount);
                 if(searchResultCount>0){
                    jobSearchObj.run().each(function(result){
                        projectDetails.owner=result.getValue({name: "custentity_jj_prj_managers", label: "Project Owner"});
                        managers.push(result.getValue({name: "projectmanager", label: "Project Manager"}))
                        return true;
                     });
                     projectDetails.managers=managers;
                 }


                 return projectDetails;
                 
                 
            }
            catch(e){
                log.error("error@projectDetails",e)
                return {};
            }
        }

        function employeeDetails(employeeId){
            try{
                let employeeSearchObj = search.create({
                    type: "employee",
                    filters:
                    [
                       ["internalid","anyof",employeeId]
                    ],
                    columns:
                    [
                       search.createColumn({name: "altname", label: "Name"})
                    ]
                 });
                 let searchResultCount = employeeSearchObj.runPaged().count;
                 log.debug("employeeSearchObj result count",searchResultCount);
                 let name=""
                 if(searchResultCount>0){
                    employeeSearchObj.run().each(function(result){
                        name =result.getValue({name: "altname", label: "Name"})
                    });
                 }
                 return name;
                 
            }
            catch(e){
                log.error("error@employeeDetails",e)
                return "";
            }
        }

        function sendEmail(emailObj){
            try{
                email.send({
                    author: 3073,
                    recipients: emailObj.receiver,
                    subject: emailObj.subject,
                    body: emailObj.body
                });
            }
            catch(e){
                log.error("error@sendEmail",e)
            }
        }
        const Record_Roles={'Pending VP Approval': 3, 	'Pending Resource Manager Approval': 1129}

        const beforeLoad = (scriptContext) => {
            try{
                let currentUser = runtime.getCurrentUser();
                if(scriptContext.type== 'create' && scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_deal_pipeline'})){
                    scriptContext.newRecord.setValue({
                        fieldId : 'custrecord_jj_rec_req_status',
                        value: 1
                    });
                    let field=scriptContext.form.getField({
                        id: 'custrecord_jj_rec_req_status'
                    })
                    log.debug("field",field)
                    field.updateDisplayType({
                        displayType : serverWidget.FieldDisplayType.DISABLED
                    });

                    scriptContext.newRecord.setValue({
                        fieldId : 'custrecord_jj_rec_req_status',
                        value: 1
                    });

                    scriptContext.newRecord.setValue({
                        fieldId : 'custrecord_jj_next_approver',
                        value: 3073
                    });                    

                }
                if(scriptContext.type ==  'view'){

                   // let currentUser = runtime.getCurrentUser();


                   let form= 171
                    log.debug("currentUser",currentUser)
                    let recordStatus=scriptContext.newRecord.getText({fieldId: 'custrecord_jj_rec_req_status'})
                    let buttonLable= "Approve"
                    if(scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_prj_parent'})){
                        buttonLable = "Approve & Allocate";
                        form=172
                    }

                    if(Record_Roles.hasOwnProperty(recordStatus) && (Record_Roles[recordStatus]==runtime.getCurrentUser().role|| runtime.getCurrentUser().role=='3')) {

                        scriptContext.form.clientScriptModulePath ='./jj_cs_req_app-butt_action_atpl252.js';
                        scriptContext.form.addButton({
                            id: 'custpage_jj_approve_button_atpl_252',
                            label: buttonLable,
                            functionName: `pendingVPVerification(${scriptContext.newRecord.id})`
                        });
    
                        scriptContext.form.addButton({
                            id: 'custpage_jj_reject_button_atpl_252',
                            label: 'Reject',
                            functionName: `pendingVPVerificationReject(${scriptContext.newRecord.id},${form})`
                        });
                    }
                   
                }
                if(scriptContext.type=='edit'&& scriptContext.request.parameters.type){
                    let field=scriptContext.form.getField({
                        id: 'custrecord_jj_rec_req_status'
                    })
                    field.updateDisplayType({
                        displayType : serverWidget.FieldDisplayType.DISABLED
                    });
                    scriptContext.form.getField({id: 'custrecord_jj_reject_reaseon'}).isMandatory = true;

                    let reasonField =  scriptContext.form.getField({
                        id: 'custrecord_jj_reject_reaseon'
                    })
                    reasonField.updateDisplayType({
                        displayType : serverWidget.FieldDisplayType.NORMAL
                    });
                }

                //Project Part

                if(scriptContext.type== 'create' && scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_prj_parent'})){
                    let field=scriptContext.form.getField({
                        id: 'custrecord_jj_rec_req_status'
                    })
                    field.updateDisplayType({
                        displayType : serverWidget.FieldDisplayType.DISABLED
                    });
                    scriptContext.newRecord.setValue({
                        fieldId: 'custrecord_jj_rec_req_status',
                        value: 2
                    })
                    let projectDetail=projectDetails(scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_prj_parent'}))
                    log.debug("projectDetails",projectDetail)

                    if(projectDetail.hasOwnProperty('owner') || projectDetail.hasOwnProperty('manager')){
                        //if(projectDetail['owner']=runtime.getCurrentUser().id && projectDetail['managers'].includes('1118')){
                        if(projectDetail['owner']!=runtime.getCurrentUser().id && projectDetail['managers'].includes(runtime.getCurrentUser().id)){
                            let typeField =  scriptContext.form.getField({
                                id: 'custrecord_jj_req_for'
                            })
                            typeField.updateDisplayType({
                                displayType : serverWidget.FieldDisplayType.DISABLED
                            });
                        }
                    }
                    scriptContext.newRecord.setValue({
                        fieldId : 'custrecord_jj_next_approver',
                        value: 3073
                    }); 

                    //else if(projectDetail.hasOwnProperty('manager')){}
                }
                
            }
            catch(e){
                log.error("error@beforeLoad",e)
            }
        }

        /**
         * Defines the function definition that is executed before record is submitted.
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {Record} scriptContext.oldRecord - Old record
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @since 2015.2
         */
        const beforeSubmit = (scriptContext) => {
            try{
                let configObj= config.load({
                    type: config.Type.COMPANY_INFORMATION
                });
                log.debug("Script Context",scriptContext.newRecord)
                let url= configObj.getValue({fieldId: 'appurl'})+"/app/common/custom/custrecordentry.nl?rectype=599&id="+scriptContext.newRecord.id;
                if((scriptContext.type=='edit'|| scriptContext.type=='xedit') && Record_Roles.hasOwnProperty(scriptContext.newRecord.getText({fieldId: 'custrecord_jj_rec_req_status'})) && scriptContext.newRecord.getValue({fieldId:'custrecord_jj_reject_reaseon'})){
                    scriptContext.newRecord.setValue({
                        fieldId: 'custrecord_jj_rec_req_status',
                        value: 5
                    })
                    let emailReciepent = scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_req_by'})
                    log.debug("emailSender",scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_req_by'}));
                    
                    let emailContents={}
                    emailContents.subject="Resource Request Has Been Rejected";
                    emailContents.body = 'Dear '+employeeDetails(scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_req_by'}))+',<br/><br/>';
                    emailContents.body +='Your resource request has been rejected. :<a href = '+url+'>Resource Request</a><br/><br/>';
                    emailContents.body += 'If you want to request another resource, please submit a new request.<br/><br/>';
                    emailContents.body += 'Thank you';
                    emailContents.receiver = scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_req_by'});
                    //emailContents.sender = 
                    log.debug("email Contents",emailContents)
                    sendEmail(emailContents);
                }
               
            }
            catch(e){
                log.error("error@beforeSubmit",e)
            }
        }

        /**
         * Defines the function definition that is executed after record is submitted.
         * @param {Object} scriptContext
         * @param {Record} scriptContext.newRecord - New record
         * @param {Record} scriptContext.oldRecord - Old record
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @since 2015.2
         */
        const afterSubmit = (scriptContext) => {
           try{
            let configObj= config.load({
                type: config.Type.COMPANY_INFORMATION
            });
            let url= configObj.getValue({fieldId: 'appurl'})+"/app/common/custom/custrecordentry.nl?rectype=599&id="+scriptContext.newRecord.id;
            if(scriptContext.type=='create' && (scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_deal_pipeline'}) || scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_prj_parent'}))){
                // log.debug("inside")
                 let emailContents={}
                 emailContents.subject="Resource Request Pending For Your Approval";
                 emailContents.body = 'Dear Viyoosh,<br/><br/>';
                 emailContents.body +='There is a resource request awaiting your approval. Please review the details and take the necessary actions:<a href = '+url+'>Resource Request</a><br/><br/><br/>';
                 emailContents.body += 'Note: When rejecting the request, please provide a mandatory reject reason.<br/><br/><br/>';
                 emailContents.body += 'Thank you'
                 emailContents.receiver = scriptContext.newRecord.getValue({fieldId: 'custrecord_jj_next_approver'});
                 //emailContents.sender = 
                 log.debug("email Contents",emailContents)
                 sendEmail(emailContents);
             }
           }
           catch(e){
            log.error("error@beforSubmit",e)
           }
        }

        return {beforeLoad, beforeSubmit, afterSubmit}

    });

Leave a comment

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