CLIENT SCRIPT TO RESTRICT TRACKING IN WEEKLY TIME SHEET

This is a client script to restrict the tracking of time in the weekly time sheet record on weekends and holidays based on the employee work calendar

/**

 * @NApiVersion 2.1

 * @NScriptType ClientScript

 */

define([‘N/currentRecord’, ‘N/search’, ‘N/log’, ‘N/record’], function (currentRecord, search, log, record) {

    // Define the mapping object

    const dayColumnMap = {

        1: { // First day of the week is Sunday

            “sunday”: “hours0”,

            “monday”: “hours1”,

            “tuesday”: “hours2”,

            “wednesday”: “hours3”,

            “thursday”: “hours4”,

            “friday”: “hours5”,

            “saturday”: “hours6”

        },

        2: { // First day of the week is Monday

            “sunday”: “hours6”,

            “monday”: “hours0”,

            “tuesday”: “hours1”,

            “wednesday”: “hours2”,

            “thursday”: “hours3”,

            “friday”: “hours4”,

            “saturday”: “hours5”

        }

    };

    function hideHoursColumnAfterSourcing(currentRec, dayColumnMap, firstDayOfWeek) {

        try {

            const sublist = currentRec.getSublist({ sublistId: ‘timeitem’ });

            const columns = dayColumnMap[firstDayOfWeek];

            for (const day in columns) {

                if (day === ‘sunday’ || day === ‘saturday’) {

                    sublist.getColumn({ fieldId: columns[day] }).isDisabled = true;

                }

            }

        } catch (e) {

            log.error(‘Error disabling hours columns:’, e);

        }

    }

    function getWorkCalendarDetails(employeeId, tranDate) {

        try {

            let month = new Date(tranDate).getMonth() + 1;

            let year = new Date(tranDate).getFullYear()

            const searchResult = search.create({

                type: “customrecord_jj_payroll_details”,

                filters: [

                    [“custrecord_jj_payroll_emp”, “anyof”, employeeId],

                    “AND”,

                    [“isinactive”, “is”, “F”],

                    “AND”,

                    [“custrecord_jj_month”, “is”, month],

                    “AND”,

                    [“custrecord_jj_year”, “is”, year]

                ],

                columns: [

                    search.createColumn({ name: “custrecord_jj_wrk_calendar”, label: “Work Calendar” }),

                    search.createColumn({ name: “custrecord_jj_firstday_workcalender”, label: “First Day” })

                ]

            }).run().getRange({ start: 0, end: 1 });

            if (searchResult.length > 0) {

                const result = searchResult[0];

                return {

                    workCalendar: result.getValue({ name: “custrecord_jj_wrk_calendar” }),

                    subsidiaryFirstDay: result.getValue({ name: “custrecord_jj_firstday_workcalender” })

                };

            }

            return false;

        } catch (err) {

            log.error(‘Error@getWorkCalendarDetails’, err);

            return false;

        }

    }

    function disableHolidays(firstDayOfWeek, workCalendarDetails) {

        try {

            const currentRec = currentRecord.get();

            const employeeId = currentRec.getValue({ fieldId: ’employee’ });

            console.log(‘FIRSTDAYOFWEEK’, firstDayOfWeek);

            // const firstDayOfWeek = firstDay === “1” ? 1 : 2;

            // console.log(‘firstDayOfWeek’,firstDayOfWeek)

            // const workCalendarDetails = getWorkCalendarDetails(employeeId);

            // console.log(‘workCalendarDetails’, workCalendarDetails);

            if (workCalendarDetails) {

                const workcalendarSearchObj = search.create({

                    type: “workcalendar”,

                    filters: [

                        [“internalid”, “anyof”, workCalendarDetails.workCalendar]

                    ],

                    columns: [

                        search.createColumn({ name: “name”, label: “Name” }),

                        search.createColumn({ name: “exceptiondate”, label: “Exception Date” }),

                        search.createColumn({ name: “exceptiondescription”, label: “Exception Description” }),

                    ]

                });

                const holidays = [];

                workcalendarSearchObj.run().each(function (result) {

                    holidays.push(result.getValue({ name: “exceptiondate” }));

                    return true;

                });

                console.log(‘holidays’, holidays);

                const weekStartDate = currentRec.getValue({ fieldId: ‘trandate’ });

                console.log(‘weekStartDate’, weekStartDate);

                const weeks = [];

                for (let i = 0; i <= 6; i++) { // Adjusted to include the start date

                    const date = new Date(weekStartDate);

                    date.setDate(date.getDate() + i);

                    const formattedDate = `${date.getDate()}/${date.getMonth() + 1}/${date.getFullYear()}`; // Format date as D/M/YYYY

                    const dayName = date.toLocaleDateString(‘en-US’, { weekday: ‘long’ }).toLowerCase();

                    weeks.push({ date: formattedDate, day: dayName });

                }

                console.log(‘weeks’, weeks);

                // Check if any week date is a holiday

                weeks.forEach(week => {

                    console.log(“week”, {

                        week: week,

                        includes: holidays.includes(week.date)

                    });

                    if (holidays.includes(week.date)) {

                        console.log(`Holiday found on ${week.day} (${week.date}).`);

                        const columnFieldId = dayColumnMap[firstDayOfWeek][week.day];

                        currentRec.getSublist({ sublistId: ‘timeitem’ }).getColumn({ fieldId: columnFieldId }).isDisabled = true;

                    }

                });

            }

        } catch (e) {

            log.error(‘Error in disableHolidays:’, e);

        }

    }

    function pageInit(scriptContext) {

        try {

            console.log(“scriptContext”, scriptContext);

            const currentRec = scriptContext.currentRecord;

            const employeeId = currentRec.getValue({ fieldId: ’employee’ });

            let tranDate = currentRec.getValue({ fieldId: ‘trandate’ });

            const workCalendarDetails = getWorkCalendarDetails(employeeId, tranDate);

            console.log(“workCalendarDetails in pageInit”, workCalendarDetails);

            if (!workCalendarDetails) {

                log.error(‘No work calendar details found for employee:’, employeeId);

                return;

            }

            const firstDay = workCalendarDetails.subsidiaryFirstDay;

            console.log(‘FIRSTDAYOFWEEK’, firstDay);

            const firstDayOfWeek = firstDay == “1” ? 1 : 2;

            hideHoursColumnAfterSourcing(currentRec, dayColumnMap, firstDayOfWeek);

            disableHolidays(firstDayOfWeek, workCalendarDetails);

        } catch (e) {

            log.error(‘Error in pageInit:’, e);

        }

    }

    return {

        pageInit: pageInit

    };

});

Leave a comment

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