We're reclaiming inactive PDIs to keep them available for active builders. Learn what's changing, who's affected, and how to protect your work. Read More

UI action condiion isn't working.

dusmantanayak
Tera Contributor

Hi,

 

Sys_properties: x_telu6_th_lenovo.send_to_lenovo_allowed_groups
Type:string
Value: {  "TH Digital Workplace - Asset Management": "c17e6401933842106402bfbd1dba1014",
  "TH Digital Workplace - Australia": "897e6401933842106402bfbd1dba1016",
  "TH Digital Workplace - Canada": "497e6401933842106402bfbd1dba1017",
  "TH Digital Workplace - India": "4d7e6401933842106402bfbd1dba101e",
  "TH Digital Workplace - UK": "c97e6401933842106402bfbd1dba1029",
  "TH Digital Workplace - US": "417e6401933842106402bfbd1dba102c",
  "TH TSM - Canada": "d97e6401933842106402bfbd1dba109c",
  "TH TSM - Global": "997e6401933842106402bfbd1dba109d"}

 

Script Include: THLenovoUtils
API Name: x_telu6_th_lenovo.THLenovoUtils
Client Callable: Yes
Script:
var THLenovoUtils = Class.create();
THLenovoUtils.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    isUserInAllowedGroups: function() {
        var property = gs.getProperty('x_telu6_th_lenovo.send_to_lenovo_allowed_groups'); // Use your actual property name
        if (!property) return false;

        try {
            var groupMap = JSON.parse(property);
            var groupIds = [];
            for (var groupName in groupMap) {
                groupIds.push(groupMap[groupName]);
            }

            var gr = new GlideRecord('sys_user_grmember');
            gr.addQuery('user', gs.getUserID());
            gr.addQuery('group', 'IN', groupIds.join(','));
            gr.setLimit(1);
            gr.query();
            return gr.hasNext();
        } catch (e) {
            gs.error('Error in function :: isUserInAllowedGroups ', "THLenovoUtils");
            return false;
        }
    },


    _getTroubleShootingWorkNotes: function(incSysId) {
        var grTSNote = new GlideRecord('sys_journal_field');
        grTSNote.addQuery('value', 'STARTSWITH', 'Additional details:');
        grTSNote.addQuery('value', 'LIKE', '%Troubleshooting Steps:%');
        grTSNote.addQuery('element_id', incSysId);
        grTSNote.query();

        if (grTSNote.next()) {
            return grTSNote.value;
        } else {
            return null;
        }
    },
    sendTroubleShootingCommentAfterCaseCreation: function(current) {
        var parts = current.correlation_id.split('-');
        var sysId = parts[1];
        try {
            var inputs = {};
            inputs['th_incident'] = current; // GlideRecord of table: incident
            inputs['correlation_id'] = sysId; // String
            //inputs['comments'] = current.description.toString(); // String
            inputs['comments'] = this._getTroubleShootingWorkNotes(current.sys_id);
            // Start Asynchronously: Uncomment to run in background. Code snippet will not have access to outputs.
            // sn_fd.FlowAPI.getRunner().subflow('x_telu6_th_lenovo.send_incident_updates_to_lenovo').inBackground().withInputs(inputs).run();

            // Execute Synchronously: Run in foreground. Code snippet has access to outputs.
            var result = sn_fd.FlowAPI.getRunner().subflow('x_telu6_th_lenovo.send_incident_updates_to_lenovo').inForeground().withInputs(inputs).run();
            var outputs = result.getOutputs();

            // Current subflow has no outputs defined.      
        } catch (ex) {
            var message = ex.getMessage();
            gs.error(message);
        }
    },

    createCaseViaSubflow: function() {
        var sys_id = this.getParameter('sysparm_sys_id'); // 1st param
        var mandatory_json = this.getParameter('sysparm_mandatory_json'); // 2nd param
        var work_notes = this.getParameter('sysparm_work_notes'); // 3rd param

        // gs.info('THLenovoUtils Parameters:\n sys_id: ' + sys_id +'\n mandatory_json: ' + mandatory_json +    '\n work_notes: ' + work_notes);

        var mandatoryData = {};
        try {
            mandatoryData = JSON.parse(mandatory_json);
        } catch (e) {
            gs.error('THLenovoUtils: Error parsing mandatory JSON: ' + e.message);
        }

        var incGR = new GlideRecord('incident');
        if (!incGR.get(sys_id)) {
            gs.warn('THLenovoUtils: Incident not found for sys_id: ' + sys_id);
            return "Incident not found";
        }

        var fieldLabels = {
            street_address: "Street Address",
            city: "City",
            state_province: "State / Province",
            country: "Country",
            pincode: "Zip/Postal Code",
            phone_number: "Phone Number"
        };

        // Convert JSON to readable string
        var mandatoryDataStr = "";
        for (var key in mandatoryData) {
            if (mandatoryData.hasOwnProperty(key)) {
                var label = fieldLabels[key] || key; // fallback to key if not in map
                mandatoryDataStr += label + ": " + mandatoryData[key] + "\n";
            }
        }

        // Add to work notes
        incGR.work_notes = "Additional details:\n" + mandatoryDataStr + "\nTroubleshooting Steps:\n" + work_notes;
        //incGR.description += "\nAdditional details:\n" + mandatoryDataStr + "\nTroubleshooting Steps:\n" + work_notes;

        incGR.update();

        // 5️⃣ Prepare inputs for Subflow
        var inputs = {
            th_incident: incGR, // Full GlideRecord
            address_info: mandatoryData, // JSON of mandatory fields
            troubleshooting_steps: work_notes // raw work_notes string
        };

        // 6️⃣ Run the subflow
        try {
            var result = sn_fd.FlowAPI.getRunner()
                .subflow('x_telu6_th_lenovo.create_case_for_lenovo') // Subflow sys_id or name
                .inForeground()
                .withInputs(inputs)
                .run();

            // gs.info('THLenovoUtils: Subflow executed. Outputs: ' + JSON.stringify(result.getOutputs()));
            return "Subflow triggered successfully for Incident " + sys_id;

        } catch (ex) {
            gs.error('THLenovoUtils: Error triggering Subflow: ' + ex.getMessage());
            return "Error triggering Subflow: " + ex.getMessage();
        }
    },


    getIDPTokenParameters: function() {
        var prop = gs.getProperty("x_telu6_th_lenovo.x_th_lenovo.oauth.credentials");
        if (!prop) {
            gs.error("[TH Lenovo] System property x_telu6_th_lenovo.x_th_lenovo.oauth.credentials not found or empty");
            throw "Missing system property x_telu6_th_lenovo.x_th_lenovo.oauth.credentials";
        }

        try {
            var configJson = JSON.parse(prop);

            // Detect environment based on instance name
            var instanceName = gs.getProperty("instance_name") || "";
            var env = 'dev'; // default fallback

            if (instanceName === 'telushealthflow') env = 'prod';
            else if (instanceName === 'telushealthflowqa') env = 'qa';
            else if (instanceName === 'telushealthflowtest') env = 'test';
            else if (instanceName === 'telushealthflowdev') env = 'dev';

            var result = configJson[env] || {};

            //gs.info('[THLenovoUtils] Environment resolved: ' + env + ', Config: ' + JSON.stringify(result));

            if (!result.base_url || !result.client_id || !result.client_secret || !result.resource_path) {
                throw "[TH Lenovo] Missing required fields (base_url, client_id, client_secret, resource_path) for environment: " + env;
            }

            return {
                environment: env,
                base_url: result.base_url,
                resource_path: result.resource_path,
                full_url: result.base_url + result.resource_path,
                grant_type: "client_credentials",
                client_id: result.client_id,
                client_secret: result.client_secret
            };

        } catch (e) {
            gs.error("[TH Lenovo] Failed to parse or resolve sys_prop x_telu6_th_lenovo.x_th_lenovo.oauth.credentials: " + e);
            throw e;
        }
    },

    getIntegrationConfig: function() {
        var configStr = gs.getProperty('x_telu6_th_lenovo.integration.environment.config');
        if (!configStr) {
            gs.error('Missing system property: x_telu6_th_lenovo.integration.environment.config');
            return {};
        }

        var configJson = {};
        try {
            configJson = JSON.parse(configStr);
        } catch (e) {
            gs.error('Invalid JSON in system property: x_telu6_th_lenovo.integration.environment.config');
            return {};
        }

        var instanceName = gs.getProperty('instance_name');
        // Examples: telushealthflow, telushealthflowqa, telushealthflowtest, telushealthflowdev

        var env = 'dev'; // default fallback
        if (instanceName === 'telushealthflow') env = 'prod';
        else if (instanceName === 'telushealthflowqa') env = 'qa';
        else if (instanceName === 'telushealthflowtest') env = 'test';
        else if (instanceName === 'telushealthflowdev') env = 'dev';

        var result = configJson[env] || {};
        // gs.info('[THLenovoUtils] Environment resolved: ' + env + ', Config: ' + JSON.stringify(result));
        return result;
    },
    getSubscriptionConfig: function() {
        var configStr = gs.getProperty('x_telu6_th_lenovo.integration.subscriptions.config');
        if (!configStr) {
            gs.error('Missing system property: x_telu6_th_lenovo.integration.subscriptions.config');
            return {};
        }

        var configJson = {};
        try {
            configJson = JSON.parse(configStr);
        } catch (e) {
            gs.error('Invalid JSON in system property: x_telu6_th_lenovo.integration.subscriptions.config');
            return {};
        }

        var instanceName = gs.getProperty('instance_name');
        // Examples: telushealthflow, telushealthflowqa, telushealthflowtest, telushealthflowdev

        var env = 'dev'; // default fallback
        if (instanceName === 'telushealthflow') env = 'prod';
        else if (instanceName === 'telushealthflowqa') env = 'qa';
        else if (instanceName === 'telushealthflowtest') env = 'test';
        else if (instanceName === 'telushealthflowdev') env = 'dev';

        var result = configJson[env] || {};
        //  gs.info('[THLenovoUtils] Environment resolved: ' + env + ', Config: ' + JSON.stringify(result));
        return result;
    },

    //for Get GCP Token-------------------------------------------------------------
    getGCPTokenConfig: function() {
        var propName = "x_telu6_th_lenovo.gcp.token.config";
        var propValue = gs.getProperty(propName);

        if (!propValue) {
            gs.error("[THLenovoUtils] Missing system property: " + propName);
            return {};
        }

        var config = {};
        try {
            config = JSON.parse(propValue);
        } catch (e) {
            gs.error("[THLenovoUtils] Invalid JSON in property " + propName + ": " + e.message);
            return {};
        }

        // Determine environment
        var instanceName = gs.getProperty('instance_name') || '';
        var env = 'dev';
        switch (instanceName) {
            case 'telushealthflow':
                env = 'prod';
                break;
            case 'telushealthflowqa':
                env = 'qa';
                break;
            case 'telushealthflowtest':
                env = 'test';
                break;
            case 'telushealthflowdev':
                env = 'dev';
                break;
            default:
                gs.warn('[THLenovoUtils] Unknown instance: ' + instanceName + ', defaulting to DEV');
        }

        var result = config[env] || {};
        if (!result.producer_account || !result.consumer_account || !result.iam_url) {
            gs.error("[THLenovoUtils] Incomplete GCP token config for environment: " + env);
        }

        gs.info("[THLenovoUtils] GCP token config resolved for environment: " + env);
        return result;
    },
    getSTSTokenParameters: function() {
        var prop = gs.getProperty("x_telu6_th_lenovo.sts_token_config");
        if (!prop) {
            gs.error("[TH Lenovo] System property x_telu6_th_lenovo.sts_token_config not found or empty");
            throw "Missing system property x_telu6_th_lenovo.sts_token_config";
        }

        try {
            var configJson = JSON.parse(prop);

            // Detect environment based on instance name
            var instanceName = gs.getProperty("instance_name") || "";
            var env = 'dev'; // default fallback

            if (instanceName === 'telushealthflow') env = 'prod';
            else if (instanceName === 'telushealthflowqa') env = 'qa';
            else if (instanceName === 'telushealthflowtest') env = 'test';
            else if (instanceName === 'telushealthflowdev') env = 'dev';

            var result = configJson[env] || {};

            // gs.info('[THLenovoUtils] Environment resolved (STS): ' + env + ', Config: ' + JSON.stringify(result));

            if (!result.audience || !result.base_url || !result.resource_path) {
                throw "[TH Lenovo] Missing required fields (audience, base_url, resource_path) for environment: " + env;
            }

            return {
                environment: env,
                audience: result.audience,
                base_url: result.base_url,
                resource_path: result.resource_path,
                full_url: result.base_url + result.resource_path
            };

        } catch (e) {
            gs.error("[TH Lenovo] Failed to parse or resolve sys_prop x_telu6_th_lenovo.sts_token_config: " + e);
            throw e;
        }
    },
   
    getAssetDetailsforAssignedTo: function() {
        var userSysID = this.getParameter('sysparm_caller_id');
        var serialNumbers = []; // 1. Use an array to collect values

        if (!userSysID) {
            return "No Caller ID provided";
        }

        var grComputer = new GlideRecord('cmdb_ci_computer');
        grComputer.addQuery('assigned_to', userSysID);
        grComputer.addActiveQuery();
        grComputer.query();

        // 2. Use 'while' instead of 'if' to iterate through all matching records
        while (grComputer.next()) {
            var sn = grComputer.getValue('serial_number');
            if (sn) {
                serialNumbers.push(sn); // 3. Add to the list
            }
        }

        // 4. Return the array joined by commas
        return serialNumbers.join(', ');
    },
    type: 'THLenovoUtils'
});

UI Action name :Send to Lenovo
table: incident
condition: !current.isNewRecord() && current.active == true && current.correlation_id.indexOf('Lenovo') != 0 && new x_telu6_th_lenovo.THLenovoUtils().isUserInAllowedGroups()

script: function sendIncidentTolenovo() {
    if (g_form.getValue('work_notes') == '') {
        var workNotes = g_form.getValue("work_notes");
        var affectedUser = g_form.getValue("u_affected_user"); // Get the caller
        var gm = new GlideModal("x_telu6_th_lenovo_modal_popup_for_work_notes");
        gm.setTitle("Incident Details");
        gm.setPreference("work_notes", workNotes);
        gm.setPreference("u_affected_user", affectedUser); // Pass the caller to the UI Page
        gm.setSize(600, 400);
        gm.render();
        return false;
    }
    //!current.isNewRecord() && current.active == true && current.correlation_id.indexOf('Lenovo') != 0 && new x_telu6_th_lenovo.THLenovoUtils().isUserInAllowedGroups()
}

 

UI Action condition : !current.isNewRecord() && current.active == true && current.correlation_id.toString().indexOf('Lenovo') == -1 && new x_telu6_th_lenovo.THLenovoUtils().isUserInAllowedGroups()

 

isn't working and making "Send to Lenovo " button visible false for everyone.

 

 

How i can make "send to lenovo" ui action button visible for TH Digital Workplace - Asset Management, TH Digital Workplace - Australia, TH Digital Workplace - Canada,
  TH Digital Workplace - India, TH Digital Workplace - UK, TH Digital Workplace - US,
  TH TSM - Canada, TH TSM - Global?

 

Thanks in advance.

 

Regards,

Dusmanta.

2 REPLIES 2

Tanushree Maiti
Tera Patron

My suggestion would be -

  • Add proper log to debug in isUserInAllowedGroups() where correct groupID is getting extracted after JSON parse and you are getting records from servicenow Table.
  • Instead of current.correlation_id.indexOf('Lenovo') != 0 , use current.correlation_id.indexOf('Lenovo') != -1 and Try

 

Please Accept the solution if it assisted you with your question & Mark this response as Helpful.
Regards
Tanushree Maiti
ServiceNow Technical Architect
LinkedIn: https://www.linkedin.com/in/tanushreemaiti

Itallo Brandão
Tera Guru

Hi @dusmantanayak ,

The issue is almost certainly a Null Pointer Exception causing your condition to crash and return false for everyone.

The Logical Conflict: Think about the process: The button is "Send to Lenovo". This implies the incident has not been sent yet. If it hasn't been sent, the correlation_id field is empty (null).

The Technical Error: In your condition, you represent this check as: current.correlation_id.toString().indexOf('Lenovo') == -1

At the exact moment you need the button (before sending), correlation_id is null. Calling .toString() on a null value throws a JavaScript error. When a UI Action condition errors out, ServiceNow hides the button.

The Fix: You must treat the field safely. Change your condition to use string coercion instead of the method:

JavaScript
 
!current.isNewRecord() && current.active == true && (current.correlation_id + '').indexOf('Lenovo') == -1 && new x_telu6_th_lenovo.THLenovoUtils().isUserInAllowedGroups()


By adding + '', you turn null into the string "null" or "", preventing the crash and allowing the script to proceed to your Group Check logic.

Regards,
Brandão.