Pass script include for UI Action

BanuMahalakshmi
Tera Contributor

Hi,

I am using one script include for UI action and Scheduled job script also. UI action button to check and update single location(passing parameter of current page) but scheduled job will check all locations and update the value.

Please advise the correction in the script, thanks in advance.

 

Script Include:

getlocationcontactissue: function()
{
    var locationname = this.getParameter('sysparm_value');
var locationGR = new GlideRecord('cmn_location');
locationGR.addQuery('u_active', true);
locationGR.addQuery('name', locationname);
locationGR.query();
while (locationGR.next()) {
    var errorMessage = '';
    var locationId = locationGR.sys_id.toString();
    errorMessage += checkContactCounts(locationId);
    errorMessage += checkifnotuserContTypes(locationId);
   locationGR.setValue('u_location_issues', errorMessage.trim());
    locationGR.update();
    return errorMessage.trim();
}

function checkContactCounts(locationId) {
    var message = '';
    var primaryContactCount = getContactCount(locationId, 'Primary Site Contact');
    if (primaryContactCount == 0) {
        message += 'Primary Site Contact is missing.' + '\n';
    } else if (primaryContactCount > 1) {
        message += 'Can have only one Primary Site Contact.' + '\n';
    }
}
};
UI Action Script:
  var location = g_form.getValue('name');
    var ga = new GlideAjax('locationcontactissue');
    ga.addParam('sysparm_name', 'getlocationcontactissue');
    ga.addParam("sysparm_value", location);
    ga.getXML(function (response) {
                var answer = response.responseXML.documentElement.getAttribute('answer');
gs.log(answer); //just validating the value
);
 
Scheduled Job:
function checklocationcontacttypeissue() {
   
   var addquery = "ISNOTEMPTY";
    var ga = new GlideAjax('locationcontactissue');
    ga.addParam('sysparm_name', 'getlocationcontactissue');
    ga.addParam("sysparm_value", addquery);
    ga.getXML();
}
6 REPLIES 6

venkat917181
Tera Expert

Issues in Your Code

  1. Script Include doesn't handle "check all locations" scenario
  2. Missing function definitions (checkifnotuserContTypes, getContactCount)
  3. Incorrect scheduled job approach (using GlideAjax server-side)
  4. Logic only processes first location (return inside while loop)

Corrected Script Include

var locationcontactissue = Class.create();
locationcontactissue.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getlocationcontactissue: function() {
        var locationname = this.getParameter('sysparm_value');
        var results = '';
        
        var locationGR = new GlideRecord('cmn_location');
        locationGR.addQuery('u_active', true);
        
        // If locationname is provided, filter by it; otherwise check all
        if (locationname && locationname != 'ISNOTEMPTY') {
            locationGR.addQuery('name', locationname);
        }
        
        locationGR.query();
        
        while (locationGR.next()) {
            var errorMessage = '';
            var locationId = locationGR.sys_id.toString();
            
            errorMessage += this.checkContactCounts(locationId);
            errorMessage += this.checkifnotuserContTypes(locationId);
            
            locationGR.setValue('u_location_issues', errorMessage.trim());
            locationGR.update();
            
            // For single location (UI Action), return the message
            if (locationname && locationname != 'ISNOTEMPTY') {
                return errorMessage.trim();
            }
            
            // For scheduled job, collect all results
            if (errorMessage.trim()) {
                results += 'Location: ' + locationGR.name + ' - ' + errorMessage.trim() + '\n';
            }
        }
        
        return results; // Return all results for scheduled job
    },

    checkContactCounts: function(locationId) {
        var message = '';
        var primaryContactCount = this.getContactCount(locationId, 'Primary Site Contact');
        
        if (primaryContactCount == 0) {
            message += 'Primary Site Contact is missing.\n';
        } else if (primaryContactCount > 1) {
            message += 'Can have only one Primary Site Contact.\n';
        }
        
        return message;
    },

    checkifnotuserContTypes: function(locationId) {
        // Add your logic here
        var message = '';
        // Your validation logic
        return message;
    },

    getContactCount: function(locationId, contactType) {
        // Add your contact counting logic here
        var contactGR = new GlideRecord('your_contact_table'); // Replace with actual table
        contactGR.addQuery('location', locationId);
        contactGR.addQuery('contact_type', contactType);
        contactGR.query();
        return contactGR.getRowCount();
    },

    type: 'locationcontactissue'
});

Corrected Scheduled Job

function checklocationcontacttypeissue() {
    // Don't use GlideAjax in scheduled jobs - call script include directly
    var checker = new locationcontactissue();
    
    var locationGR = new GlideRecord('cmn_location');
    locationGR.addQuery('u_active', true);
    locationGR.query();
    
    while (locationGR.next()) {
        var locationId = locationGR.sys_id.toString();
        var errorMessage = '';
        
        errorMessage += checker.checkContactCounts(locationId);
        errorMessage += checker.checkifnotuserContTypes(locationId);
        
        locationGR.setValue('u_location_issues', errorMessage.trim());
        locationGR.update();
        
        if (errorMessage.trim()) {
            gs.log('Location issues found for ' + locationGR.name + ': ' + errorMessage.trim());
        }
    }
}

Key Changes

  1. Added logic to handle both single location and all locations
  2. Fixed scheduled job to call script include directly (not via GlideAjax)
  3. Moved functions inside the script include class
  4. Added proper return logic for different scenarios
  5. Added missing function stubs that you need to implement

Note: You need to implement the missing functions (checkifnotuserContTypes, getContactCount) with your actual business logic.

Thanks for reply, i tried this script into scheduled job and am getting 'undefined' value into scheduled job.

Ankur Bawiskar
Tera Patron
Tera Patron

@BanuMahalakshmi 

so you want same script include function to be called from GlideAjax and also from scheduled job so that you can reuse

use this

1) also call script include function defined within same script include using the syntax this.functionName

    // Main method callable from both UI Action (via GlideAjax) and Scheduled Job
    getLocationContactIssue: function(locationName) {

            var locationName = JSUtil.nil(locationName) ? this.getParameter('sysparm_value') : locationName;

            var results = [];
            var locationGR = new GlideRecord('cmn_location');
            locationGR.addQuery('u_active', true);

            // If a location name is provided, process only that location
            if (locationName && locationName != 'ALL') {
                locationGR.addQuery('name', locationName);
            }
            locationGR.query();
            while (locationGR.next()) {
                var errorMessage = '';
                var locationId = locationGR.getUniqueValue();
                errorMessage += this.checkContactCounts(locationId);
                errorMessage += this.checkIfNotUserContTypes(locationId);
                locationGR.setValue('u_location_issues', errorMessage.trim());
                locationGR.update();
                results.push({
                    location: locationGR.name.toString(),
                    issues: errorMessage.trim()
                });
            }
            // Return results for GlideAjax
            return JSON.stringify(results);
        },

        checkContactCounts: function(locationId) {
            var message = '';
            // Implement your logic here
            var primaryContactCount = this.getContactCount(locationId, 'Primary Site Contact');
            if (primaryContactCount == 0) {
                message += 'Primary Site Contact is missing.\n';
            } else if (primaryContactCount > 1) {
                message += 'Can have only one Primary Site Contact.\n';
            }
            return message;
        },

        checkIfNotUserContTypes: function(locationId) {
            // Implement your logic here
            return '';
        },

        getContactCount: function(locationId, contactType) {
            // Implement your logic here
            return 0;
        },

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,

Thanks for reply, multiple functions used inthis script. As per your suggestion, i have included this.function name in my script. i have tried to print the errormessage into logs but its execute. pls let me know correction in this script: thanks.

var locationcontactissue = Class.create();
locationcontactissue.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    getlocationcontactissue: function() {
 
        var results = [];
        var locationname = JSUtil.nil(locationname) ? this.getParameter('sysparm_value') : locationname;
        var locationGR = new GlideRecord('cmn_location');
        locationGR.addQuery('u_active', true);

       if (locationname && locationname != '') {
            gs.log("inside the loop");
            locationGR.addQuery('name', locationname);
        }

locationGR.query();
while (locationGR.next()) {
var errorMessage = '';
var locationId = locationGR.sys_id.toString();
errorMessage += this.checkContactCounts(locationId);
errorMessage += this.checkifnotuserContTypes(locationId);
errorMessage += this.checkifnotgroupContTypes(locationId);
errorMessage += this.checkotherContactTypes(locationId);
errorMessage += this.checkgrpContactTypes(locationId);

gs.log("the erromessage="+errorMessage.trim());

locationGR.setValue('u_location_contact_issues', errorMessage.trim());
locationGR.update();
},

checkContactCounts: function (locationId) {
var message = '';
var primaryContactCount = getContactCount(locationId, 'Primary Site Contact');
if (primaryContactCount == 0) {
message += 'Primary Site Contact is missing.' + '\n';
} else if (primaryContactCount > 1) {
message += 'Can have only one Primary Site Contact.' + '\n';
}var HRITContact = getContactCount(locationId, 'HR IT Contact');
if (HRITContact == 0) {
message += 'HR IT Contact is missing.' + '\n';
}
return message;
},

getContactCount: function(locationId, contactType) {
var contactGR = new GlideAggregate('u_location_point_of_contact');
contactGR.addQuery('u_location', locationId);
contactGR.addQuery('u_contact_type', contactType);
contactGR.addQuery('u_active', true);
contactGR.addAggregate('COUNT');
contactGR.query();
while (contactGR.next()) {
return contactGR.getAggregate('COUNT');
}
},

function checkifnotuserContTypes(locationId) {
var msg = '';
if (!this.validateContactType(locationId, 'Primary Site Contact', ['User'])) {
msg += 'Primary Site Contact type must be user.' + '\n';
}
if (!this.validateContactType(locationId, 'Secondary Site Contact', ['User'])) {
msg += 'Secondary Site Contact type must be user.' + '\n';
}
return msg;
}

checkifnotgroupContTypes:function(locationId) {
var msg = '';
if (this.validateContactType(locationId, 'Local Support', ['Group'])) {
msg += 'Local Support type must be group.' + '\n';
}
return msg;
},

checkotherContactTypes: function(locationId) {
var msg = '';
if (!this.validateContactType(locationId, 'Primary Network Contact', ['Other'])) {
msg += 'Primary Network Contact must be user or group.' + '\n';
}

return msg;
},

checkgrpContactTypes: function(locationId) {
var msg = '';
if (!this.validateContactType(locationId, 'Primary Off-Hours Contact', ['Group'])) {
msg += 'Primary Off-Hours Contact must be user or other.' + '\n';
}

return msg;
},

validateContactType:function(locationId, contactType, allowedTypes) {
var type = allowedTypes[0];
var gr = new GlideRecord('u_location_point_of_contact');
gr.addQuery('u_location', locationId);
gr.addQuery('u_contact_type', contactType);
gr.addQuery('u_active', true);
gr.query();

while (gr.next()) {
var typeValue = gr.getValue('u_group_user');
if (type == "User") {
if (!allowedTypes.includes(typeValue)) {
return false;
}
}
if (type == "Other") {
if (allowedTypes.includes(typeValue)) {
return false;
}
}
if (type == "Group") {
if (allowedTypes.includes(typeValue)) {
return false;
}
}
}
return true;
},
});