Auto populate values to Weekly Time Sheet

Scenario

When a project record is selected then we have to auto populate the division and activity code values from the project record.

Solution

/**
 * @NApiVersion 2.1
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/************************************************************************************************
 * CLIENT NAME : International Planned Parenthood Federation
 * IPPF- 1228 Restriction based on Project Allocation record
 * IPPF- 1323 Auto populate values to Weekly Time Sheet
 *********************************************************************************************
 *
 * Author: Jobin and Jismi IT Services
 * Date Created : 27-April-2023
 * Created By: Aswathy, Jobin and Jismi IT Services
 * Description : Script for Restriction based on Project Allocation record
 *
 * REVISION HISTORY
 * Revision 1.0 - 27 April 2023 - Restriction based on Project Allocation record
 * Revision 2.0 - 09 May 2023 - Auto populate values to Weekly Time Sheet
 ***********************************************************************************************/
define(['N/currentRecord', 'N/record', 'N/search','N/format'],
    /**
     * @param{currentRecord} currentRecord
     * @param{record} record
     * @param{search} search
     * @param{format} format
     */
    function(currentRecord, record, search,format) {

        /**
         * Function to check the Project Allocation
         * @param customer
         * @returns {*[]}
         */
        function searchProjectAllocation(customers)
        {
            try
            {
                let customrecord_jj_project_allocSearchObj = search.create({
                    type: "customrecord_jj_project_alloc",
                    filters:
                        [
                            ["custrecord_jj_project","anyof",customers],
                            "AND",
                            ["isinactive","is","F"]
                        ],
                    columns:
                        [
                            search.createColumn({name: "custrecord_jj_project", label: "Project"}),
                            search.createColumn({name: "custrecord_jj_project_period", label: "Payroll Record"})
                        ]
                });
                let searchResultCount = customrecord_jj_project_allocSearchObj.runPaged().count;
                let payRollArray =[];
                if(searchResultCount > 0)
                {
                    customrecord_jj_project_allocSearchObj.run().each(function(result){
                        payRollArray.push(result.getValue({
                            name: "custrecord_jj_project_period", label: "Payroll Record"
                        }))

                        return true;
                    });
                    console.log("payRollArray",payRollArray)
                    return payRollArray;
                }
                else
                {
                    return []
                }
            }
            catch(err)
            {
                console.log("error@searchProjectAllocation",err)
                return [];
            }
        }

        /**
         * Funtion to check the availability of a payroll record
         * @param checkProjectAllocation
         * @param employee
         * @param monthsArray
         * @param yearArray
         * @returns {*[]}
         */
        function payRollAllocationSearch(checkProjectAllocation, employee, monthsArray, yearArray)
        {
            try
            {
                let customrecord_jj_payroll_detailsSearchObj = search.create({
                    type: "customrecord_jj_payroll_details",
                    filters:
                        [
                            ["custrecord_jj_payroll_emp","anyof",employee],
                            "AND",
                            ["custrecord_jj_month","anyof",monthsArray],
                            "AND",
                            ["custrecord_jj_year","is",yearArray],
                            "AND",
                            ["internalid","anyof",checkProjectAllocation],
                            "AND",
                            ["isinactive","is","F"]
                        ],
                    columns:
                        [
                            search.createColumn({name: "custrecord_jj_monthly_rate", label: "Monthly Rate"}),
                            search.createColumn({name: "custrecord_jj_month", label: "Month"}),
                            search.createColumn({name: "custrecord_jj_year", label: "Year"}),
                            search.createColumn({
                                name: "custrecord_jj_pro_activity_code",
                                join: "CUSTRECORD_JJ_PROJECT_PERIOD",
                                label: "Project Activity Code"
                            }),
                            search.createColumn({
                                name: "custrecord_jj_proj_div",
                                join: "CUSTRECORD_JJ_PROJECT_PERIOD",
                                label: "Project Division"
                            }),
                            search.createColumn({
                                name: "internalid",
                                sort: search.Sort.DESC,
                                label: "Internal ID"
                            })
                        ]
                });
                let searchResultCount = customrecord_jj_payroll_detailsSearchObj.runPaged().count;
                let dataArray = [];
                if(searchResultCount > 0)
                {
                    customrecord_jj_payroll_detailsSearchObj.run().each(function(result){
                        let dataObj = {};
                        dataObj.activityCode = result.getValue({
                            name: "custrecord_jj_pro_activity_code",
                            join: "CUSTRECORD_JJ_PROJECT_PERIOD",
                            label: "Project Activity Code"
                        });
                        dataObj.division =  result.getValue({
                                name: "custrecord_jj_proj_div",
                                join: "CUSTRECORD_JJ_PROJECT_PERIOD",
                                label: "Project Division"
                        });
                        dataArray.push(dataObj)
                        return true;
                    });
                return dataArray;
                }
                else
                {
                    return []
                }

            }
            catch(err)
            {
                console.log("error@payRollAllocationSearch",err)
                return []
            }
        }

        /**
         * 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 be executed when field is slaved.
         *
         * @param {Object} scriptContext
         * @param {Record} scriptContext.currentRecord - Current form record
         * @param {string} scriptContext.sublistId - Sublist name
         * @param {string} scriptContext.fieldId - Field name
         *
         * @since 2015.2
         */
        function postSourcing(scriptContext) {

            try
            {

                if(scriptContext.fieldId == 'customer')
                {

                    let currentRecord = scriptContext.currentRecord;
                    let recordType = currentRecord.type;
                    let sublistName = scriptContext.sublistId;
                    let sublistFieldName = scriptContext.fieldId;
                    let weekDay = currentRecord.getValue({
                        fieldId:'trandate'
                    })
                    let employee = currentRecord.getValue({
                        fieldId:"employee"
                    });
                    let weekDayDate = new Date(weekDay);
                    let startMonth = (weekDayDate.getMonth()) + 1
                    let startYear = weekDayDate.getFullYear();
                    let lastWeekDayDate = new Date(weekDayDate.setDate(weekDayDate.getDate() + 7))
                    let gmtLastWeekDayDate = format.format({
                        value: lastWeekDayDate,
                        type: format.Type.DATETIME,
                        timezone: format.Timezone.GMT
                    });
                    let endMonth = gmtLastWeekDayDate.split('/');
                    let endMonthValue = endMonth[1];
                    let endYear = (endMonth[2]).split(' ')
                    let endYearValue = endYear[0];
                    let monthsArray = [];
                    let yearArray = [];
                    let flag = true;
                    let flagValue = true;
                    monthsArray.push(startMonth, endMonthValue);
                    yearArray.push(startYear, endYearValue);

                    if(recordType === 'timesheet') {
                        if( sublistName == 'timeitem' && sublistFieldName == 'customer') {

                            let customers = currentRecord.getCurrentSublistValue({
                                sublistId: 'timeitem',
                                fieldId: 'customer',
                            });

                            if(!customers)
                            {
                                return false;
                            }
                            let checkProjectAllocation = searchProjectAllocation(customers);
                            if(checkProjectAllocation.length > 0)
                            {

                                let checkPayRoll = payRollAllocationSearch(checkProjectAllocation, employee, monthsArray, yearArray);
                                 console.log("checkPayRoll",checkPayRoll)
                                if(checkPayRoll.length > 0)
                                    {
                                       
                                            if(checkForParameter(checkPayRoll[0].activityCode)){
                                                currentRecord.setCurrentSublistValue({
                                                    sublistId: 'timeitem',
                                                    fieldId: 'department',
                                                    value: checkPayRoll[0].activityCode
                                                })
                                            }
                                            if(checkForParameter(checkPayRoll[0].activityCode)){
                                                currentRecord.setCurrentSublistValue({
                                                    sublistId: 'timeitem',
                                                    fieldId: 'class',
                                                    value: checkPayRoll[0].division
                                                })
                                            }
                                       
                                    }
                                    else
                                    {
                                        alert("You do not have permission to choose the project since the project allocation record for this month has not been created.")
                                        currentRecord.setCurrentSublistValue({
                                            sublistId: 'timeitem',
                                            fieldId: 'customer',
                                            value: ''
                                        })
                                        flag = false
                                        return false;

                                    }
                            }
                            else
                            {
                                alert("You do not have permission to choose the project since the project allocation record for this month has not been created.")
                                currentRecord.setCurrentSublistValue({
                                    sublistId: 'timeitem',
                                    fieldId: 'customer',
                                    value: ''
                                })
                                flagValue = false
                                return false;
                            }

                        }
                    }

                }
            }
            catch(err)
            {
                console.log("error@postSourcing",err)
            }

        }
        return {
            postSourcing:postSourcing
        };

    });

Leave a comment

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