USER EVENT SCRIPT THAT CALCULATES THE DATE BASED ON THE TERMS

This user event script sample is used to calculate the date value and set these to a custom date field based on the terms with reference to the transaction date.

define(['N/record', 'N/search'], (record, search) => {


    // Utility function to parse D/M/YYYY to JavaScript Date object
    function parseDMYToDate(dateStr) {
        try {
            let [day, month, year] = dateStr.split('/').map(Number);
            return new Date(year, month - 1, day); // Months are zero-indexed
        } catch (e) {
            log.error('Error in parseDMYToDate:', e);
        }
    }


    // Utility function to format JavaScript Date to D/M/YYYY
    function formatDateToDMY(date) {
        try {
            let day = date.getDate();
            let month = date.getMonth() + 1;
            let year = date.getFullYear();


            day = day < 10 ? `0${day}` : day;
            month = month < 10 ? `0${month}` : month;


            return `${day}/${month}/${year}`;
        } catch (e) {
            log.error('Error in formatDateToDMY:', e);
        }
    }


    // Utility function to add days to a date
    function addDays(date, days) {
        try {
            let result = new Date(date);
            result.setDate(result.getDate() + days);
            return result;
        } catch (e) {
            log.error('Error in addDays:', e);
        }
    }


    // Utility function to get the first day of the third month after a given date
    function getFirstDayOfThirdMonth(date) {
        try {
            let result = new Date(date);
            result.setMonth(result.getMonth() + 3, 1);
            return result;
        } catch (e) {
            log.error('Error in getFirstDayOfThirdMonth:', e);
        }
    }


    // Utility function to set a specific day of a following or same month
    function setSpecificDay(date, monthsToAdd, dayOfMonth) {
        try {
            let result = new Date(date);
            result.setMonth(result.getMonth() + monthsToAdd, dayOfMonth);
            return result;
        } catch (e) {
            log.error('Error in setSpecificDay:', e);
        }
    }


    // Main function to calculate a new transaction date based on terms
    function calculateNewTranDate(tranDate, terms) {
        try {
            let currentDate = parseDMYToDate(tranDate);


            switch (terms) {
                case "120 days":
                    return formatDateToDMY(addDays(currentDate, 120));
                case "14 days":
                    return formatDateToDMY(addDays(currentDate, 14));
                case "1st of 3 months following":
                    return formatDateToDMY(getFirstDayOfThirdMonth(currentDate));
                case "20th Month Following":
                    return formatDateToDMY(setSpecificDay(currentDate, 1, 20));
                case "20th of same month":
                    return formatDateToDMY(setSpecificDay(currentDate, 0, 20));
                case "20th of two months following":
                    return formatDateToDMY(setSpecificDay(currentDate, 2, 20));
                case "30 days":
                    return formatDateToDMY(addDays(currentDate, 30));
                case "30th Month Following":
                    return formatDateToDMY(setSpecificDay(currentDate, 1, 30));
                case "30th of two months following":
                    return formatDateToDMY(setSpecificDay(currentDate, 2, 30));
                case "45 Days from Invoice":
                    return formatDateToDMY(addDays(currentDate, 45));
                case "60 days":
                    return formatDateToDMY(addDays(currentDate, 60));
                case "7 days":
                    return formatDateToDMY(addDays(currentDate, 7));
                case "90 days":
                    return formatDateToDMY(addDays(currentDate, 90));
                case "97 days":
                    return formatDateToDMY(addDays(currentDate, 97));
                case "Cash":
                    return formatDateToDMY(currentDate);
                default:
                    throw new Error(`Unsupported term: ${terms}`);
            }
        } catch (e) {
            log.error('Error in calculateNewTranDate:', e);
        }
    }


    const afterSubmit = (scriptContext) => {
        try {
            // Only trigger on record creation
            if (scriptContext.type === scriptContext.UserEventType.CREATE) {
                let recordObj = scriptContext.newRecord;


                // Lookup fields for terms and transaction date
                let lookUpFields = search.lookupFields({
                    type: search.Type.PURCHASE_ORDER,
                    id: recordObj.id,
                    columns: ['terms', 'trandate']
                });


                log.debug('Lookup Fields Result', lookUpFields);


                let tranDate = lookUpFields["trandate"];
                let termsArray = lookUpFields["terms"];
                log.debug('tran date',tranDate)


                if (!tranDate) {
                    log.debug('Transaction Date Missing', 'TranDate not found in lookup fields.');
                    return;
                }


                if (termsArray && termsArray.length > 0) {
                    let termsText = termsArray[0]["text"];
                    log.debug('Terms Text', termsText);


                    // Calculate new transaction date based on terms
                    let updatedTranDate = calculateNewTranDate(tranDate, termsText);


                    if (updatedTranDate) {
                        record.submitFields({
                            type: record.Type.PURCHASE_ORDER,
                            id: recordObj.id,
                            values: {
                                custbody_oo_est_due_received_by: updatedTranDate
                            },
                        });


                        log.debug('Successfully Set Updated Date: dateValue', updatedTranDate);
                    } else {
                        log.debug('No Date Change Needed', 'Terms did not require a date change.');
                    }
                } else {
                    log.debug('Terms Missing', 'No terms found for the record.');
                }
            }
        } catch (e) {
            log.error('Error in afterSubmit Script', e);
        }
    };


    return { afterSubmit };
});

Leave a comment

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