Automated Status Synchronization for Linked Records

Scenario: When a record (charity/vendor) has changed its fields (such as charity status), then automatically update the corresponding statuses in the attached project records.

Use the following code:

/**
 * @NApiVersion 2.1
 * @NScriptType UserEventScript
 */
/*******************************************************************************************************
 * TRUST BRIDGE GLOBAL FOUNDATION | TRS
 *
 * TRUST-3452: Update Project Status to 'Project Suspended' When Charity Status is 'Suspended'
 ******************************************************************************************************
 * AUTHOR        :  JOBIN AND JISMI IT SERVICES LLP
 * CREATED BY    :  JENCY
 * CREATED DATE  :  04th JULY 2021
 * JIRA CODE     :  TRUST-3452
 * INSTANCE      :  DIAB SANDBOX 
 * DESCRIPTION   :  This script is used to update Project Status to 'Project Suspended' When Charity Status is 'Suspended'
 *
 * REVISON HISTORY
 * TRUST-3712 | Update Project GSM Field after changing the GSM Field value in the Vendor/Charity record. | 02 May 2024 | JENCY WILSON  (Swiss task)
 * TRUST-3909 || NET-4183 [DIAB]Update project status to ‘Project Paused’ if Parent Charity is changed to ineligible charity statuses | 20 december 2024 | JENCY WILSON
 *
 *****************************************************************************************************/
define(['N/record', 'N/search'],
    /**
     * @param{record} record
     */
    (record, search) => {


        "use strict";
        const SUSPENDED = 10; // charity status = suspended
        const PROJECT_SUSPENDED = 10; // project status = Project suspended
        const INELIGIBLE_CHARITY_STATUS = [7, 8, 9, 12]; // charity status = Expired – Active, Expired – Inactive, Application Denied, Not Proceeding
        const PROJECT_PAUSED = 11; // project status = project paused
        const PROJECT_COMPLETED = 6; // project status = project paused


        /**
            * @description Check whether the given parameter argument has value on it or is it empty.
            * ie, To check whether a value exists in parameter
            * @param {*} parameter parameter which contains/references some values
            * @param {*} parameterName name of the parameter, not mandatory
            * @returns {Boolean} true if there exist a value else false
            */
        function checkForParameter(parameter, parameterName) {
            try {
                if (parameter !== "" && parameter !== null && parameter !== undefined && parameter !== false && parameter !== "null" && parameter !== "undefined" && parameter !== " " && parameter !== 'false') {
                    return true;
                } else {
                    if (parameterName)
                        log.debug('Empty Value found', 'Empty Value for parameter ' + parameterName);
                    return false;
                }
            } catch (e) {
                log.debug('error@checkForParameter', e)
                log.error('error@checkForParameter', e)
                return false;
            }
        }


        /**
         * To fetch all the projects connected to the selected vendor
         * @param {*} vendorId 
         * @returns 
         */
        function getAllRelatedProjects(vendorId) {
            try {
                let projectsArray = [];
                let vendorSearchObj = search.create({
                    type: "vendor",
                    filters:
                        [
                            ["internalid", "anyof", vendorId],
                            "AND",
                            ["custrecord_project_parent_charity.internalid", "noneof", "@NONE@"]
                        ],
                    columns:
                        [
                            search.createColumn({
                                name: "internalid",
                                join: "CUSTRECORD_PROJECT_PARENT_CHARITY",
                                label: "Internal ID"
                            }),
                            search.createColumn({
                                name: "name",
                                join: "CUSTRECORD_PROJECT_PARENT_CHARITY",
                                label: "Name"
                            }),
                            search.createColumn({
                                name: "custrecord_project_status",
                                join: "CUSTRECORD_PROJECT_PARENT_CHARITY",
                                label: "Project Status"
                            }),
                        ]
                });
                let searchResultCount = vendorSearchObj.runPaged().count;
                vendorSearchObj.run().each(function (result) {
                    projectsArray.push(result.getValue(vendorSearchObj.columns[0]))
                    return true;
                });
                return projectsArray;
            } catch (e) {
                log.debug('error@getAllRelatedProjects', e)
                log.error('error@getAllRelatedProjects', e)
                return false;
            }
        }


        /**
         * Set the field values based on the conditions
         * @param relatedProjects 
         * @param fields 
         * @returns 
         */
        function setSubmitField(relatedProjects, fields, newCharityStatus) {
            try {
                if (checkForParameter(relatedProjects.length)) {
                    for (let i = 0; i < relatedProjects.length; i++) {
                        for (var key in fields) {
                            if (checkForParameter(key) && (key == 'custrecord_project_status')) {
                                var projectStatusValue = search.lookupFields({
                                    type: 'customrecord_projects',
                                    id: relatedProjects[i],
                                    columns: ['custrecord_project_status']
                                });
                                let currentProjectStatus = projectStatusValue.custrecord_project_status[0].value;
                                if ((Number(currentProjectStatus) === PROJECT_COMPLETED) && (checkForParameter(newCharityStatus)) && INELIGIBLE_CHARITY_STATUS.includes(Number(newCharityStatus))) {
                                    fields.custrecord_project_status = PROJECT_COMPLETED;
                                }
                            }
                        }
                        record.submitFields({
                            type: 'customrecord_projects',
                            id: relatedProjects[i],
                            values: fields,
                        });
                    }
                }
            } catch (e) {
                log.debug('error@setProjectFields', e)
                log.error('error@setProjectFields', e)
                return false;
            }
        }


        /**
         * To set the project field values according to the changes with the Project Parent Cahrity.
         * @param {*} scriptContext 
         * @param {*} oldRecord 
         * @param {*} newRecord 
         * @param {*} vendorId 
         * @returns 
         */
        function setProjectFields(scriptContext, oldRecord, newRecord, vendorId) {
            try {
                let oldCharityStatus = '';


                if (scriptContext.type !== scriptContext.UserEventType.CREATE) {
                    oldCharityStatus = oldRecord.getValue({
                        fieldId: 'custentity_charity_status'
                    });
                }
                let newCharityStatus = newRecord.getValue({
                    fieldId: 'custentity_charity_status'
                });
                if ((oldCharityStatus != newCharityStatus)) {
                    let relatedProjects = getAllRelatedProjects(vendorId);
                    if (relatedProjects.length) {
                        if ((oldCharityStatus != newCharityStatus)) {
                            if ((newCharityStatus == SUSPENDED) || (INELIGIBLE_CHARITY_STATUS.includes(Number(newCharityStatus)))) {
                                let setNewProjectStatus = (INELIGIBLE_CHARITY_STATUS.includes(Number(newCharityStatus))) ? PROJECT_PAUSED : PROJECT_SUSPENDED
                                let values = {
                                    custrecord_project_status: setNewProjectStatus,
                                    custrecord_project_parent_charity_status: newCharityStatus,
                                };
                                setSubmitField(relatedProjects, values, newCharityStatus);
                            } else {
                                let values = {
                                    custrecord_project_parent_charity_status: newCharityStatus,
                                };
                                setSubmitField(relatedProjects, values, newCharityStatus);
                            }
                        }
                    }
                }
            } catch (e) {
                log.debug('error@setProjectFields', e)
                log.error('error@setProjectFields', e)
                return false;
            }
        }


        const main = {


            /**
             * 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 record
             * @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
             * @since 2015.2
             */
            afterSubmit: (scriptContext) => {
                try {
                    let vendorId = scriptContext.newRecord.id;
                    let oldRecord = scriptContext.oldRecord;
                    let newRecord = scriptContext.newRecord;
                    let setProjectFieldValues = setProjectFields(scriptContext, oldRecord, newRecord, vendorId);
                } catch (e) {
                    log.debug('error@afterSubmit', e);
                    log.error('error@afterSubmit', e);
                }
            }
        }
        return main;
    });

Leave a comment

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