Delegation Approval Real-Time Process

Scenario

 When an employee create a delegation record same as to the current date/ less than the current date then the delegation record is created with the status as “In Progress”  with the delegate person value based on the availablity of either supervisor/ div head / admin person after submitting the record. Then the time approver field of all the subordinates of the corresponding employee is set as the delegate person value. And the Stand in Approver field of the employee who request the delegation will set with delegate person value. And the check box Unable to Approve is also set as checked. Also it will send an email to the delegation person that he has received a delegation request.  

During this active record creation time, if the employee has already a delegate person in any other active delegation record, we will update these delegtion records with the higher level employees based on corresponding employee. If any of the records are updated then the time approver field of the subordinates is also updated. If any time the delegating person is changed we will send an email to the delegating person.  

Solution

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */

/***********************************************************************************************
 * CLIENT NAME : International Planned Parenthood Federation
 * IPPF-1342 Employee Delegation Approval (V2)
 * IPPF-1399 Employee Delegation V3
 * *********************************************************************************************
 * Date : 22-05-2023
 *
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : This user event script is used to Delegate the responsibility to employees
 * Date created :  22-05-2023
 * Created by: Aswathy Viswanathan, Jobin & Jismi IT Services LLP
 * REVISION HISTORY
 * Revision 1.0 ${22-05-2023} :Employee Delegation Approval
 * Revised by : Aswathy Viswanathan, Jobin & Jismi IT Services LLP

 ***************************************************************************************************/
define(['N/runtime', 'N/ui/serverWidget', 'N/record', 'N/search', 'N/email', 'N/format'],
    /**
     * @param{runtime} runtime
     * @param{serverWidget} serverWidget
     * @param{record} record
     * @param{search}search
     *  @param{email}email
     *  @param{format}format  
     * 
     */
    (runtime, serverWidget, record, search, email, format) => {

              

                /**
                * Const varibale values
                */  
                const ADMIN_PERSON = 18521;
                const ADMIN_EMAIL = 'svineeth@ippf.org';
                const ADMIN_NAME = 'EMP1211 Surya Vineeth';
                 const ROLES_OBJECT = {
                    ADMIN: '3',
                }
               
        /**
         * Function to get the subordinates of the current employee
         * @param employee
         * @returns {*[]}
         */

        function subordinateSearch(employeeArray) {
            try {
                let employeeSearchObj = search.create({
                    type: "employee",
                    filters:
                        [
                            ["supervisor", "is", employeeArray],
                            "AND", 
                            ["isinactive","is","F"],
                            "AND", 
                            ["releasedate","isempty",""]
                            // "AND",
                            // ["internalid","anyof","18679"]
                        ],
                    columns:
                        [
                            search.createColumn({name: "internalid", label: "Internal ID"}),
                            search.createColumn({name: "supervisor", label: "Supervisor"}),
                            search.createColumn({name: "timeapprover", label: "Time Approver"})
                        ]
                });
                let searchResultCount = employeeSearchObj.runPaged().count;
                log.debug("searchResultCount", searchResultCount)
                let subordinateArray = []
                if (searchResultCount > 0) {

                    employeeSearchObj.run().each(function (result) {
                        let subordinateObj = {};
                        subordinateObj.subId = result.getValue({
                            name: "internalid", label: "Internal ID"
                        })
                        subordinateObj.supervisor = result.getValue({
                            name: "supervisor", label: "Supervisor"
                        })
                        subordinateObj.timeApprover = result.getValue({
                            name: "timeapprover", label: "Time Approver"
                        })

                        subordinateArray.push(subordinateObj)

                        return true;
                    });

                    
                    return subordinateArray;
                } else {
                    return []
                }

            } catch (err) {
                log.debug("error@FunctionsubordinateSearch", err)
            }
        }
        
        /**
         * Function for check for parameter
         * @param {*} parameter 
         * @returns {boolean}
         */

        const checkForParameter = function checkForParameter(parameter) {

            if (parameter !== "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== " " && parameter !== 'false' && parameter !== 0 && parameter !== '0') {
                return true;
            }

        }

        /**
         * Function to get the employee name
         * @param employee
         * @returns {boolean|*}
         */
        function empNameSearch(employee) {
            try {
                let employeeSearchObj = search.create({
                    type: "employee",
                    filters:
                        [
                            ["internalid", "is", employee],
                            "AND", 
                            ["isinactive","is","F"], 
                            "AND", 
                            ["releasedate","isempty",""]
                        ],
                    columns:
                        [
                            search.createColumn({name: "internalid", label: "Internal ID"}),
                            search.createColumn({name: "altname", label: "Name"}),


                        ]
                });
                let searchResultCount = employeeSearchObj.runPaged().count;
                let empName
                if (searchResultCount > 0) {
                    employeeSearchObj.run().each(function (result) {

                        empName = result.getValue({
                            name: "altname", label: "Name"
                        });
                        return true;
                    });
                    return empName;
                } else {
                    return false
                }
            } catch (err) {
                log.debug("error@empNameSearch", err)
            }
        }

       
       /**
         * Function to check if an employee is assigned to any active delegation request of his subordinates
         * @param employee
         * @returns {*[]}
         */

        function checkEmployeeHasActiveDelegation(employee)
        {
            try
            {
               let customrecord_jj_emp_delgSearchObj = search.create({
                    type: "customrecord_jj_emp_delg",
                    filters:
                        [
                            ["custrecord_jj_delegation_status","anyof","2"],
                            "AND",
                            ["custrecord_jj_delegateto_delg","anyof",employee],
                            "AND", 
                            ["isinactive","is","F"], 
                        ],
                    columns:
                        [
                            search.createColumn({
                                name: "name",
                                sort: search.Sort.ASC,
                                label: "ID"
                            }),
                            search.createColumn({name: "internalid", label: "Internal ID"}),
                            search.createColumn({name: "custrecord_jj_empname_delg", label: "Employee Name"}),
                            search.createColumn({name: "custrecord_jj_delegateto_delg", label: "Delegate To"}),
                            search.createColumn({name: "custrecord_jj_delg_start", label: "Delegation Start Date"}),
                            search.createColumn({name: "custrecord_jj_delg_end", label: "Delegation End Date"}),
                            search.createColumn({name: "custrecord_jj_emp_supervsr", label: "Employee Supervisor"}),
                            search.createColumn({name: "custrecord_jj_div_head", label: "Division Head"}),
                            search.createColumn({name: "custrecord_jj_head_drtr_email", label: "Division head Email"}),
                            search.createColumn({name: "custrecord_jj_delegation_status", label: "Delegation Status"})

                        ]
                });
              let searchResultCount = customrecord_jj_emp_delgSearchObj.runPaged().count;
              let activeEmpArray =[]
                if(searchResultCount > 0)
                {
                    customrecord_jj_emp_delgSearchObj.run().each(function(result){
                        let activeEmpObj = {}
                        activeEmpObj.recordId = result.getValue({
                            name: "internalid", label: "Internal ID"
                        });
                        activeEmpObj.empName = result.getValue({
                            name: "custrecord_jj_empname_delg", label: "Employee Name"
                        });
                        activeEmpObj.empNameText = result.getText({
                            name: "custrecord_jj_empname_delg", label: "Employee Name"
                        });
                        activeEmpObj.supervisor = result.getValue({
                            name: "custrecord_jj_emp_supervsr", label: "Employee Supervisor"
                        });
                        activeEmpObj.empDivHead = result.getValue({
                            name: "custrecord_jj_div_head", label: "Division Head"
                        });
                        activeEmpObj.empDivHeadText = result.getText({
                            name: "custrecord_jj_div_head", label: "Division Head"
                        });
                        activeEmpObj.empDivHeadEmail = result.getValue({
                            name: "custrecord_jj_head_drtr_email", label: "Division head Email"
                        });
                        activeEmpObj.deleEndDate = result.getValue({
                            name: "custrecord_jj_delg_end", label: "Delegation End Date"
                        });
                        activeEmpObj.status = result.getValue({
                            name: "custrecord_jj_delegation_status", label: "Delegation Status"
                        });
                        activeEmpArray.push(activeEmpObj);
                        return true;
                    });
                    return activeEmpArray;
                }
                else
                {
                    return []
                }

            }
            catch(err)
            {
                log.debug("error@checkEmployeeHasActiveDelegation",err)
            }
        }

    

     /**
     * Function to check the check the available supervisor
     * @param supervisor
     * @returns {*[]}
     */


function checkAvailabilityOfEmployee(employeeArray)
{
    try
    {
        let customrecord_jj_emp_delgSearchObj = search.create({
            type: "customrecord_jj_emp_delg",
            filters:
            [
               ["custrecord_jj_empname_delg","anyof",employeeArray], 
               "AND", 
               ["custrecord_jj_delegation_status","anyof","2"], 
               "AND", 
               ["isinactive","is","F"]
            ],
            columns:
            [
               search.createColumn({name: "internalid", label: "Internal ID"}),
               search.createColumn({name: "custrecord_jj_empname_delg", label: "Employee Name"}),

            ]
         });
         let searchResultCount = customrecord_jj_emp_delgSearchObj.runPaged().count;
         let resultArray = [];
         if(searchResultCount > 0)
         {
            customrecord_jj_emp_delgSearchObj.run().each(function(result){
                let resultObj = {}
                resultObj.internalID = result.getValue({
                    name: "internalid", label: "Internal ID"  
                })
                resultObj.employee =  result.getValue({
                    name: "custrecord_jj_empname_delg", label: "Employee Name" 
                })
                resultObj.employeeText =  result.getText({
                    name: "custrecord_jj_empname_delg", label: "Employee Name" 
                })
                resultArray.push(resultObj);
                return true;
             });

             return resultArray;
         }
         else
         {
            return [];
         }
       
         }
    catch(err)
    {
       log.debug("error@checkAvailabilityOfSupervisor",err)
       return []
    }
}

/**
 * Function to process Active delegation
 * @param {*} checkActiveDelegation 
 * @param {*} finalGMTStartDate 
 * @param {*} finalGMTEndDate 
 * @param {*} supervisorEmail 
 * @param {*} finalCurrentdate 
 */
      

function processActiveDelegation(checkActiveDelegation, finalGMTStartDate, finalGMTEndDate,supervisorEmail, finalCurrentdate)
                {
                    try{
                        
                        let divHeadArray=[];
                        let availabilty; 
                        let delegateArray = [];
                        let delegateArrayDivHead = [];
                        let resultArray = [];
                        let emailContent;

                        for(let i = 0 ; i < checkActiveDelegation.length ; i++)
                        {
                       
                            if(checkForParameter(checkActiveDelegation[i].empDivHead))
                            {
                                divHeadArray.push(checkActiveDelegation[i].empDivHead)
                            }   
                       
                        
                        }
    
                        
                        if(divHeadArray.length > 0)
                        {
                            availabilty = checkAvailabilityOfEmployee(divHeadArray);
                            log.debug("availabilty",availabilty);
                           
                            if(availabilty.length > 0) 
                            {
                                  
                                for(let i = 0 ; i < checkActiveDelegation.length ; i++)
                                {
                                    for(let j= 0 ;j < availabilty.length; j++)
                                    {
                                        let emailObj = {}
                                       
                                        if(checkActiveDelegation[i].empDivHead === availabilty[j].employee)
                                        {
                                            
                                         
                                            emailObj.recordId = checkActiveDelegation[i].recordId;
                                            emailObj.employee = checkActiveDelegation[i].empName;
                                            emailObj.employeeName = checkActiveDelegation[i].empNameText;
                                            emailObj.delegatePerson = ADMIN_PERSON;
                                            emailObj.delegateEmail = ADMIN_EMAIL;
                                            emailObj.delegateName = ADMIN_NAME;
                                            emailObj.status = checkActiveDelegation[i].status
                                            delegateArray.push(emailObj)
                                            
                                        }
            
                                        else
                                        {
                                            
                                            emailObj.recordId = checkActiveDelegation[i].recordId;
                                            emailObj.employee = checkActiveDelegation[i].empName;
                                            emailObj.employeeName = checkActiveDelegation[i].empNameText;
                                            emailObj.delegatePerson =checkActiveDelegation[i].empDivHead
                                            emailObj.delegateEmail = checkActiveDelegation[i].empDivHeadEmail
                                            emailObj.delegateName = checkActiveDelegation[i].empDivHeadText
                                            emailObj.status = checkActiveDelegation[i].status
                                            emailObj.deleEndDate = checkActiveDelegation[i].deleEndDate
                                            delegateArray.push(emailObj)
                                            
                                        }
                                    }
                                 
        
                                } 
    
                                
                            }
    
                            else
                            {  
                             for(let i = 0 ; i < checkActiveDelegation.length ; i++){
                     
                                 let emailObject = {}
                     
                                 emailObject.recordId = checkActiveDelegation[i].recordId;
                                 emailObject.employee = checkActiveDelegation[i].empName;
                                 emailObject.employeeName = checkActiveDelegation[i].empNameText;
                                 emailObject.delegatePerson =checkActiveDelegation[i].empDivHead
                                 emailObject.delegateEmail = checkActiveDelegation[i].empDivHeadEmail
                                 emailObject.delegateName = checkActiveDelegation[i].empDivHeadText
                                 emailObject.status = checkActiveDelegation[i].status
                                 emailObject.deleEndDate = checkActiveDelegation[i].deleEndDate
                                 delegateArrayDivHead.push(emailObject)
                             }
                            }
    
    
                    }

                    else

                    {
                        for(let i = 0 ; i < checkActiveDelegation.length ; i++){

                        let resultObj = {};
                        resultObj.recordId = checkActiveDelegation[i].recordId;
                        resultObj.employee = checkActiveDelegation[i].empName;
                        resultObj.employeeName = checkActiveDelegation[i].empNameText;
                        resultObj.delegatePerson = ADMIN_PERSON;
                        resultObj.delegateEmail = ADMIN_EMAIL;
                        resultObj.delegateName = ADMIN_NAME;
                        resultObj.status = checkActiveDelegation[i].status
                        resultObj.deleEndDate = checkActiveDelegation[i].deleEndDate
                        resultArray.push(resultObj)

                        }


                    }

                    if(delegateArray.length > 0)
                    {
                      processDelegateArray(delegateArray, finalGMTStartDate, finalGMTEndDate, supervisorEmail, finalCurrentdate)
                    }
                    
                    if(delegateArrayDivHead.length > 0)
                    {
                      processDelegateArray(delegateArrayDivHead, finalGMTStartDate, finalGMTEndDate, supervisorEmail, finalCurrentdate)
                    }
                    
                    if(resultArray.length > 0)
                    {
                        processDelegateArray(resultArray, finalGMTStartDate, finalGMTEndDate, supervisorEmail, finalCurrentdate)
                    }
                        
                    }
                    catch(err)
                    {
                        log.debug("error@processActiveDelegation",err)
                    }
                }
               


  /**
   * Function to send email if the employee has other active delegation records.
   * @param {*} delegateArray 
   * @param {*} startDate 
   * @param {*} supervisorEmail 
   */

  function processDelegateArray(delegateArray, startDate, finalGMTEndDate, supervisorEmail, finalCurrentdate)
  {
    try{
        log.debug("finalCurrentdate7",finalCurrentdate)
        let delegatePersonArray = []; 
  
        if(delegateArray.length > 0)
        {
            for(let i = 0 ; i < delegateArray.length ; i++)
            {
                if(checkForParameter(delegateArray[i].employee)){
                    delegatePersonArray.push(delegateArray[i].employee)
                }
                
                if(delegateArray[i].status == '2'){
                    
                  
                        let empCode = (delegateArray[i].employeeName).substring(0, (delegateArray[i].employeeName).indexOf(' '));
                        let emailNames = (delegateArray[i].employeeName).split(empCode);                                   
                        let emailName = emailNames[1]
                        
                        let empCodeDelegatePerson = (delegateArray[i].delegateName).substring(0, (delegateArray[i].delegateName).indexOf(' '));
                        let emailNamesDelegatePerson = (delegateArray[i].delegateName).split(empCodeDelegatePerson);                                   
                        let emailNameDelegatePerson = emailNamesDelegatePerson[1];
  
                        record.submitFields({
                        type: 'customrecord_jj_emp_delg',
                        id: delegateArray[i].recordId,
                        values: {
                            'custrecord_jj_delegateto_delg': delegateArray[i].delegatePerson
                        },
                        options: {
                            enableSourcing: false,
                            ignoreMandatoryFields: true
                        }
                    });
  
  
                    record.submitFields({
                        type: record.Type.EMPLOYEE,
                        id:delegateArray[i].employee,
                        values: {
                            custentity_stand_in_app: delegateArray[i].delegatePerson
                        },
                        options: {
                            enableSourcing: false,
                            ignoreMandatoryFields: true
                        }
                    });
                    
                   
                     emailContent = 'Hi ' + emailNameDelegatePerson + ',' + '<br/>' + 'You have been delegated responsibility of ' + emailName + ' from ' + finalCurrentdate + ' to ' + delegateArray[i].deleEndDate + '.' + '<br/>' + '<br/>' + 'Thank you!'
                     
                     email.send({
                        author: delegateArray[i].employee,
                        recipients: delegateArray[i].delegateEmail,
                        cc: supervisorEmail,
                        subject: 'Delegation Request',
                        body: emailContent,
                        relatedRecords: {
                            entityId:delegateArray[i].delegatePerson,
                            customRecord: {
                                id:delegateArray[i].recordId,
                                recordType: 530 //an integer value
                            }
                        }
                    });
                      
                }
                
               
            }
        }
    if(delegatePersonArray.length > 0)
    {
        let newSubordinates = subordinateSearch(delegatePersonArray);
        if(newSubordinates.length > 0)
        {
            for(let i = 0 ; i < newSubordinates.length ; i++)
            {
                for(let j = 0; j < delegateArray.length ; j++)
                {
                    if(newSubordinates[i].supervisor === delegateArray[j].employee)
                    {
                        record.submitFields({
                            type: record.Type.EMPLOYEE,
                             id:  newSubordinates[i].subId,
                             values: {
                                timeapprover: delegateArray[j].delegatePerson
                                
                           },
                             options: {
                             enableSourcing: false,
                             ignoreMandatoryFields: true
                             }
                 
                           });
                    }
                }
               
            }     
        }
    }
           
    }
    catch(err)
    {
        log.debug("error@processDelegateArray",err)
    }
  }




   /**
    * Function that process Employee delegation process
    * @param {*} delegateFrom 
    * @param {*} currentRecord 
    * @param {*} startDateArrayCompare 
    * @param {*} currentDateArrayCompare 
    * @param {*} supervisor 
    * @param {*} divHead 
    * @param {*} superEmail 
    * @param {*} divHeadEmail 
    * @param {*} supervisorEmail 
    * @param {*} empText 
    * @param {*} finalGMTStartDate 
    * @param {*} finalGMTEndDate 
    * 
    */


                function processEmployeeDelegation(delegateFrom, currentRecord, startDateArrayCompare, currentDateArrayCompare, supervisor, divHead, superEmail, divHeadEmail, supervisorEmail,empText, finalGMTStartDate, finalGMTEndDate, finalCurrentdate)
                {
                  try{
                      log.debug("finalCurrentdate2",finalCurrentdate)
                      let delegatePerson, delegateEmail;
               
                      if (startDateArrayCompare <= currentDateArrayCompare) 
                      {
  
                      if(checkForParameter(supervisor))
                      {
                      let supervisorArray = [];
                      supervisorArray.push(supervisor)                        
                      supervisorText = empNameSearch(supervisor)
                      if(supervisorText === false || supervisorText == 'false')
                      {
                         return true;
                      }
                      let availableSupervisor = checkAvailabilityOfEmployee(supervisorArray);
                      if(availableSupervisor.length > 0)
                      {
                          
                          if(checkForParameter(divHead))
                          { 
                              let divHeadarray = [];
                              divHeadarray.push(divHead)
                              divHeadText = empNameSearch(divHead)
                              if(divHeadText === false || divHeadText == 'false')
                              {
                                 return true
                              }
                              let availableDivHead = checkAvailabilityOfEmployee(divHeadarray);
                              log.debug("availableDivHead",availableDivHead);
                              if(availableDivHead.length > 0)
                              {
                                 let adminText = empNameSearch(ADMIN_PERSON)
                                 if(adminText === false || adminText == 'false')
                                 {
                                    return true
                                 }
                                 else{

                                    delegatePerson = ADMIN_PERSON;
                                    delegateEmail = ADMIN_EMAIL; 
                                 }
                                       
                              }
                              else
                              { 
                                  delegatePerson = divHead;
                                  delegateEmail = divHeadEmail 
  
                              }
  
                         }
                      }
  
                      
                      else
                      {
                        delegatePerson = supervisor;
                        delegateEmail = superEmail
                      }
  
                    }

                    else
                    { 
                        
                        let adminText = empNameSearch(ADMIN_PERSON)
                                 if(adminText === false || adminText == 'false')
                                 {
                                    return true
                                 }
                                 else{
                                    
                                    delegatePerson = ADMIN_PERSON;
                                    delegateEmail = ADMIN_EMAIL; 
                                    supervisorEmail.push(ADMIN_EMAIL)
                                 }
                    }

  
                      log.debug("delegatePerson",delegatePerson);
                      log.debug("delegateEmail",delegateEmail);
  
                                   record.submitFields({
                                      type: 'customrecord_jj_emp_delg',
                                      id: currentRecord.id,
                                      values: {
                                       'custrecord_jj_delegateto_delg': delegatePerson,
                                       'custrecord_jj_delegate_email': delegateEmail,
                                       'custrecord_jj_delegation_status': 2
                                    },
                                    options: {
                                      enableSourcing: false,
                                      ignoreMandatoryFields: true
                                      }
                                    });
                                                                    
                                    record.submitFields({
                                      type: record.Type.EMPLOYEE,
                                       id: delegateFrom,
                                       values: {
                                           custentity_stand_in_app: delegatePerson,
                                           custentity_unable_to_approve : true
                                     },
                                       options: {
                                       enableSourcing: false,
                                       ignoreMandatoryFields: true
                                       }
                           
                                     });
                          
                 
                     if(checkForParameter(delegatePerson))
                     {
                      let delegatePersonText = empNameSearch(delegatePerson);
                         
                      let emailBody = 'Hi ' + delegatePersonText + ',' + '<br/>' + 'You have been delegated responsibility of ' + empText + ' from ' + finalGMTStartDate + ' to ' + finalGMTEndDate + '.' + '<br/>' + '<br/>' + 'Thank you!'                            
                      if(!delegateEmail)
                      {
                          return false;
                      }
                      if(delegatePerson === supervisor)
                      {
                         email.send({
                                      author:delegateFrom,
                                      recipients: delegateEmail,
                                      // cc:supervisorEmail,
                                      subject: 'Delegation Request',
                                      body: emailBody,
                                      relatedRecords: {
                                          entityId: delegatePerson,
                                          customRecord: {
                                              id: currentRecord.id,
                                              recordType: 530 //an integer value
                                          }
                                      }
                                  });
                      }
                      
                      else
                      {
                        log.debug("supervisorEmail",supervisorEmail)
                           email.send({
                                      author: delegateFrom,
                                      recipients: delegateEmail,
                                      cc:supervisorEmail,
                                      subject: 'Delegation Request',
                                      body: emailBody,
                                      relatedRecords: {
                                          entityId: delegatePerson,
                                          customRecord: {
                                              id: currentRecord.id,
                                              recordType: 530 //an integer value
                                          }
                                      }
                                  });
                      }
                      let delegateEmpArray = [];
                      delegateEmpArray.push(delegateFrom)
                    
                     let subordiantes = subordinateSearch(delegateEmpArray);                    
                      if(subordiantes.length > 0)
                      {
                          for(let i = 0 ; i < subordiantes.length ; i++)
                          {
                              record.submitFields({
                                  type: record.Type.EMPLOYEE,
                                   id:  subordiantes[i].subId,
                                   values: {
                                      timeapprover: delegatePerson,
                                      
                                 },
                                   options: {
                                   enableSourcing: false,
                                   ignoreMandatoryFields: true
                                   }
                       
                                 });
                          }
                      }  
                     }
                         
  
                    /**
                     *  Check that the current employee has another delegation record. 
                    * */  
                   
                  let checkActiveDelegation = checkEmployeeHasActiveDelegation(delegateFrom);
                  log.debug("checkActiveDelegation",checkActiveDelegation);
  
                  if(checkActiveDelegation.length > 0)
                  {
                    log.debug("finalCurrentdate3",finalCurrentdate)
                      let processArray = processActiveDelegation(checkActiveDelegation, finalGMTStartDate, finalGMTEndDate, supervisorEmail, finalCurrentdate)
                      
                  }
  
                 }
  
                 else
                 {
                          
                   record.submitFields({
                     type: 'customrecord_jj_emp_delg',
                     id: currentRecord.id,
                     values: {
                     'custrecord_jj_delegation_status': 1
                     },
                    options: {
                    enableSourcing: false,
                    ignoreMandatoryFields: true
                     }
                    });
  
                }

                }

                  catch(err)
                  {
                      log.debug("error@processEmployeeDelegation",err)
                  }
                }

              /**
               * Function to Process Date
               * @param {*} dateValue 
               * @returns {string}
               */

                function processDate(dateValue)
                {
                    try{

                        let gmtDelegateDate = format.format({
                            value: dateValue,
                            type: format.Type.DATETIME,
                            timezone: format.Timezone.GMT
                        });
                        let startDateText = gmtDelegateDate.split(' ')
                        let delegationStartDateText = startDateText[0];

                        return delegationStartDateText;
                    }
                    catch(err)
                    {
                        log.debug("error@ProcessDate",err)
                    }
                }



        /**
         * 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{
                let currentUser = runtime.getCurrentUser().role;
                let currentform = scriptContext.form;
                let employee = currentform.getField({
                    id: 'custrecord_jj_empname_delg'
                });
                let delegateEmployee = currentform.getField({
                    id: 'custrecord_jj_delegateto_delg'
                });
                let currentRecord = scriptContext.newRecord; 
                let status = currentRecord.getValue({
                    fieldId: 'custrecord_jj_delegation_status'
                });
                let startDate = currentform.getField({
                    id: 'custrecord_jj_delg_start'
                });
                let endDate = currentform.getField({
                    id: 'custrecord_jj_delg_end'
                });
                if(currentUser != ROLES_OBJECT.ADMIN){
                    delegateEmployee.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                }
                if(scriptContext.type == 'edit'){


                    employee.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
               
                if(status == '3')
                {
                    startDate.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });

                    endDate.updateDisplayType({
                        displayType: serverWidget.FieldDisplayType.DISABLED
                    });
                }

                }
      
            }
            catch(err)
            {
                log.debug("error@beforeLoad",err)
            }
        }


        /**
         * 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 recheckForParametercord
         * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
         * @since 2015.2
         */
        const afterSubmit = (scriptContext) => {


            try {
               
                let currentRecord = scriptContext.newRecord;               
                let delegateFrom = currentRecord.getValue({
                    fieldId: 'custrecord_jj_empname_delg'
                });              
                let empText,supervisorText,divHeadText;
                if(checkForParameter(delegateFrom))
                {
                    empText = empNameSearch(delegateFrom);
                   if(empText === false || empText == 'false')
                   {
                       return true;
                   }
                
                let delegationStartDate = currentRecord.getValue({
                    fieldId: 'custrecord_jj_delg_start'
                }); 
                let compareCurrentDate;
                let delegationStartDateText = processDate(delegationStartDate);
                let currentDayDate = new Date()
                let finalCurrentdate = processDate(currentDayDate);
                log.debug("finalCurrentdate",finalCurrentdate)
                if(delegationStartDateText == finalCurrentdate)
                {
                    
                    compareCurrentDate = delegationStartDate
                }
                else
                {
                    compareCurrentDate = currentDayDate
                }

                let delgationEndDate = currentRecord.getValue({
                    fieldId: 'custrecord_jj_delg_end'
                });
               
                let delgationEndDateText = processDate(delgationEndDate)
                log.debug("delgationEndDateText",delgationEndDateText)
            
        
                let supervisor = currentRecord.getValue({
                    fieldId: 'custrecord_jj_emp_supervsr'
                });
                 let superEmail = currentRecord.getValue({
                    fieldId: 'custrecord_jj_supervsr_email'
                });
                let supervisorEmail = [];
                if(checkForParameter(superEmail))
                {
                    supervisorEmail.push(superEmail);
                }
                
                 let divHead = currentRecord.getValue({
                    fieldId: 'custrecord_jj_div_head'
                });
                let divHeadEmail = currentRecord.getValue({
                    fieldId: 'custrecord_jj_head_drtr_email'
                });               
                let startDateArrayCompare = new Date(delegationStartDate).getTime();
                let currentDateArrayCompare = new Date(compareCurrentDate).getTime();
                let endDateCompare = new Date(delgationEndDate).getTime();
                let startDateCompare = new Date(currentDayDate).getTime();               
                
               if(scriptContext.type == 'create')
               {
                  processEmployeeDelegation(delegateFrom, currentRecord, startDateArrayCompare, currentDateArrayCompare, supervisor, divHead, superEmail, divHeadEmail, supervisorEmail, empText, delegationStartDateText, delgationEndDateText, finalCurrentdate)
                 
               } 
       
              if(scriptContext.type == 'edit'){
              let oldRecordData = scriptContext.oldRecord;
              let status = currentRecord.getValue({
                fieldId:'custrecord_jj_delegation_status'
              });
                                         
             let oldStartDate = oldRecordData.getValue({
                fieldId:'custrecord_jj_delg_start'
             });
             let oldEndDate = oldRecordData.getValue({
                fieldId:'custrecord_jj_delg_end'
             });
             let oldStartDateCompare = new Date(oldStartDate).getTime();
             let oldEndDateCompare = new Date(oldEndDate).getTime();
                         
                if((oldStartDateCompare != startDateArrayCompare) || (oldEndDateCompare != endDateCompare))
                {
                    if(status == '3')
                    {   
                     return false;
                    }
               
                if ((startDateArrayCompare <= currentDateArrayCompare) && (endDateCompare > startDateCompare))
                 {
                 
                   record.submitFields({
                    type: 'customrecord_jj_emp_delg',
                    id: currentRecord.id,
                    values: {
                    
                     'custrecord_jj_delegation_status': 2
                  },
                  options: {
                    enableSourcing: false,
                    ignoreMandatoryFields: true
                    }
                  });
                      
                 processEmployeeDelegation(delegateFrom, currentRecord,startDateArrayCompare, currentDateArrayCompare, supervisor,divHead, superEmail, divHeadEmail, supervisorEmail, empText, delegationStartDateText, delgationEndDateText, finalCurrentdate)
               
                } 
                
                else if(startDateArrayCompare > currentDateArrayCompare)
                {
                  log.debug("else condition.")
                    
                    record.submitFields({
                        type: 'customrecord_jj_emp_delg',
                        id: currentRecord.id,
                        values: {
                        
                         'custrecord_jj_delegation_status': 1
                      },
                      options: {
                        enableSourcing: false,
                        ignoreMandatoryFields: true
                        }
                      });
  
  
                      let delegateFromArray = [];
                      delegateFromArray.push(delegateFrom)
                                       record.submitFields({
                                          type: 'customrecord_jj_emp_delg',
                                          id:currentRecord.id,
                                          values: {
                                              'custrecord_jj_delegateto_delg': " "
                                          },
                                          options: {
                                              enableSourcing: false,
                                              ignoreMandatoryFields: true
                                          }
                                      });
                      let empSubordinates = subordinateSearch(delegateFromArray);
                                      
                      if(empSubordinates.length > 0)
                      {
                          for(let i = 0 ;i < empSubordinates.length; i++)
                          {
                              log.debug("subordinates[i].subId",empSubordinates[i].subId)
                             
                              record.submitFields({
                                  type: record.Type.EMPLOYEE,
                                  id: empSubordinates[i].subId,
                                  values: {
                                      timeapprover : ""
                                  },
                                  options: {
                                      enableSourcing: false,
                                      ignoreMandatoryFields : true
                                  }
                              });
                          }
                      }
  

                }              
            
            }
         
            
         }
    
                
    }
             
            } catch (err) {
                log.debug("error@AfterSubmit", err)
            }
        }

        return { beforeLoad,afterSubmit}

    });

Leave a comment

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