Delegation Approval Process – Scheduled Processing

Scenario

If an employee create a delegation record, whose delegation start date is not equal to the current date, then the delegation record is created with the status as “Planned”. 

The emails and other time approver fields are set only when the delegation record is get active.  

This is achieved by using a Scheduled script. This script will check if any delegation records delegation start date is Today. And then get the data and process the data in the same manner.  

The delegation record is updated 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 MapReduceScript
 */
/***********************************************************************************************
 * 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 map reduce 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/email', 'N/record', 'N/search','N/format'],
    /**
 * @param{email} email
 * @param{record} record
 * @param{search} search
     *  @param{format}format
 */
    (email, record, search,format) => {


                /**
                * Const varibale values
                */  
                const ADMIN_PERSON = '18521';
                const ADMIN_EMAIL = 'svineeth@ippf.org';
                const ADMIN_NAME = 'EMP1211 Surya Vineeth'; 
       
                /**
         * Function to check the employeee delegation start date from the custom record Employee Delegation
         * @returns {*[]}
         */

         function checkEmployeeDelegationStartDate()
         {
             try
             {
                 let customrecord_jj_emp_delgSearchObj = search.create({
                     type: "customrecord_jj_emp_delg",
                     filters:
                         [
                             ["custrecord_jj_delg_start","on","today"],
                             "AND", 
                            ["isinactive","is","F"],
                            "AND", 
                            ["custrecord_jj_delegation_status","noneof","3"],


                         ],
                     columns:
                         [
                             search.createColumn({
                                 name: "name",
                                 sort: search.Sort.ASC,
                                 label: "ID"
                             }),
                             search.createColumn({name: "scriptid", label: "Script 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_div", label: "Employee Division"}),
                             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_supervsr_email", label: "Supervisor Email"}),
                             search.createColumn({name: "custrecord_jj_emp_supervsr", label: "Employee Supervisor"}),
                             search.createColumn({name: "custrecord_jj_delg_start", label: "Delegation Start Date"}),
                             search.createColumn({name: "custrecord_jj_delg_end", label: "Delegation End Date"})


                         ]
                 });
                 let searchResultCount = customrecord_jj_emp_delgSearchObj.runPaged().count;
                 let employeeArray =[];
                if(searchResultCount > 0)
                {
                    customrecord_jj_emp_delgSearchObj.run().each(function(result){
                        let empObj={};
                        empObj.customRecId= result.getValue({
                            name: "internalid", label: "Internal ID"
                        });
                        empObj.empName= result.getValue({
                            name: "custrecord_jj_empname_delg", label: "Employee Name"
                        });
                        empObj.empText=result.getText({
                            name: "custrecord_jj_empname_delg", label: "Employee Name"
                        });
                        empObj.startDate = result.getText({
                            name: "custrecord_jj_delg_start", label: "Delegation Start Date"
                        });
                        empObj.endDate = result.getText({
                            name: "custrecord_jj_delg_end", label: "Delegation End Date"
                        });
                        empObj.delegatePerson =  result.getValue({
                            name: "custrecord_jj_delegateto_delg", label: "Delegate To"
                        });
                        empObj.delegatePersonText =  result.getText({
                            name: "custrecord_jj_delegateto_delg", label: "Delegate To"
                        });
                        empObj.supervisor = result.getValue({
                            name: "custrecord_jj_emp_supervsr", label: "Employee Supervisor"
                        });
                        empObj.supervisorEmail = result.getValue({
                            name: "custrecord_jj_supervsr_email", label: "Supervisor Email"
                        });
                        empObj.divHead = result.getValue({
                            name: "custrecord_jj_div_head", label: "Division Head"
                        });
                        empObj.divHeadEmail= result.getValue({
                            name: "custrecord_jj_head_drtr_email", label: "Division head Email"
                        });
                        empObj.startDate= result.getValue({
                            name: "custrecord_jj_delg_start", label: "Delegation Start Date"
                        });
                        empObj.endDate= result.getValue({
                            name: "custrecord_jj_delg_end", label: "Delegation End Date"
                        });

                        employeeArray.push(empObj)
                        return true;
                    });
                    return employeeArray
                }
                else
                {
                    return []
                }



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


         /**
         * 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;
                
                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 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 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 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 check the availability of an employee
   * @param {} employeeArray 
   * @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 if the the employee has other active delegation records
  * @param {*} checkActiveDelegation 
  * @param {*} startDate 
  * @param {*} endDate 
  * @param {*} supervisorEmail 
  */

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

          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
                              emailObj.deleEndDate = checkActiveDelegation[i].deleEndDate
                              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)

              }


          }

        
  
      log.debug("delegateArray",delegateArray);
      log.debug("delegateArrayDivHead",delegateArrayDivHead);     
      if(delegateArray.length > 0)
      {
        processDelegateArray(delegateArray, startDate,supervisorEmail, finalCurrentdate)
      }
      
      if(delegateArrayDivHead.length > 0)
      {
        processDelegateArray(delegateArrayDivHead, startDate, supervisorEmail, finalCurrentdate)
      }  
      if(resultArray.length > 0)
      {
          processDelegateArray(resultArray, startDate, 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, supervisorEmail, finalCurrentdate)
  {
    try{

        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 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 that is executed at the beginning of the map/reduce process and generates the input data.
         * @param {Object} inputContext
         * @param {boolean} inputContext.isRestarted - Indicates whether the current invocation of this function is the first
         *     invocation (if true, the current invocation is not the first invocation and this function has been restarted)
         * @param {Object} inputContext.ObjectRef - Object that references the input data
         * @typedef {Object} ObjectRef
         * @property {string|number} ObjectRef.id - Internal ID of the record instance that contains the input data
         * @property {string} ObjectRef.type - Type of the record instance that contains the input data
         * @returns {Array|Object|Search|ObjectRef|File|Query} The input data to use in the map/reduce process
         * @since 2015.2
         */

        const getInputData = (inputContext) => {

            try
            {
                let data = checkEmployeeDelegationStartDate();
                log.debug("data",data)

                return data;

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

        }



        /**
         * Defines the function that is executed when the reduce entry point is triggered. This entry point is triggered
         * automatically when the associated map stage is complete. This function is applied to each group in the provided context.
         * @param {Object} reduceContext - Data collection containing the groups to process in the reduce stage. This parameter is
         *     provided automatically based on the results of the map stage.
         * @param {Iterator} reduceContext.errors - Serialized errors that were thrown during previous attempts to execute the
         *     reduce function on the current group
         * @param {number} reduceContext.executionNo - Number of times the reduce function has been executed on the current group
         * @param {boolean} reduceContext.isRestarted - Indicates whether the current invocation of this function is the first
         *     invocation (if true, the current invocation is not the first invocation and this function has been restarted)
         * @param {string} reduceContext.key - Key to be processed during the reduce stage
         * @param {List<String>} reduceContext.values - All values associated with a unique key that was passed to the reduce stage
         *     for processing
         * @since 2015.2
         */
        const reduce = (reduceContext) => {


            try
            {
                let dataObj = reduceContext.values.map(JSON.parse);
                let customRecId = dataObj[0].customRecId
                let employee = dataObj[0].empName;
                let empArray = [];
                let empText,supervisorText,divHeadText;
                let divHeadEmail = dataObj[0].divHeadEmail;
                let superEmail = dataObj[0].supervisorEmail;
                let startDate = dataObj[0].startDate
                let endDate = dataObj[0].endDate
                let supervisorEmail = [];
                
                if(checkForParameter(superEmail))
                {
                    supervisorEmail.push(superEmail);
                }
                let delegatePerson, delegateEmail;
                let currentDayDate = new Date();
                let finalCurrentdate = processDate(currentDayDate);
                if(checkForParameter(employee))
                {
                    empArray.push(employee);
                    log.debug("empArray",empArray);
                 
                    empText = empNameSearch(employee);
                    if(empText === false || empText == 'false')
                    {
                        return true;
                    }
                    let supervisor= dataObj[0].supervisor;
                    let divHead= dataObj[0].divHead;
                    
                    if(checkForParameter(supervisor))
                    {
                        let supervisorArray = [];
                        supervisorArray.push(supervisor)
                        supervisorText = empNameSearch(supervisor)
                        if(supervisorText === false || supervisorText == 'false')
                        {
                           return true
                        }
                        let availableSupervisor = checkAvailabilityOfEmployee(supervisorArray);
                        log.debug("availableSupervisor",availableSupervisor);
                        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);
                              
                              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: customRecId,
                        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: employee,
                         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 ' + startDate + ' to ' + endDate + '.' + '<br/>' + '<br/>' + 'Thank you!'       
                        
                        if(!delegateEmail)
                        {
                            return false;
                        }
                        if(delegatePerson === supervisor)
                        {
                           email.send({
                                        author:employee,
                                        recipients: delegateEmail,
                                        // cc:supervisorEmail,
                                        subject: 'Delegation Request',
                                        body: emailBody,
                                        relatedRecords: {
                                            entityId: delegatePerson,
                                            customRecord: {
                                                id:customRecId,
                                                recordType: 530 //an integer value
                                            }
                                        }
                                    });
                        }
                        
                        else
                        {
                            
                             email.send({
                                        author: employee,
                                        recipients: delegateEmail,
                                        cc:supervisorEmail,
                                        subject: 'Delegation Request',
                                        body: emailBody,
                                        relatedRecords: {
                                            entityId: delegatePerson,
                                            customRecord: {
                                                id:customRecId,
                                                recordType: 530 //an integer value
                                            }
                                        }
                                    });
                        }
                        let delegateEmpArray = [];
                        delegateEmpArray.push(employee)
                       
                        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
                                     }
                         
                                   });
                            }
                        }  
                       }

                  let checkActiveDelegation = checkEmployeeHasActiveDelegation(employee);
                  log.debug("checkActiveDelegation",checkActiveDelegation);
                 
                  if(checkActiveDelegation.length > 0)
                  {
                      let processArray = processActiveDelegation(checkActiveDelegation, startDate, endDate, supervisorEmail, finalCurrentdate);
                     
                }                       
                
                }
                
            }
            catch(err)
            {
                log.debug("error@Reduce",err)
            }

        }
     

        return {getInputData, reduce}

    });

Leave a comment

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