You frequently need to retrieve active incidents assigned to a specific user

purnendutiw
Tera Contributor

I have one scenario for practice:

 

You frequently need to retrieve active incidents assigned to a specific user. Write a Script Include that accepts a user ID and returns a list of active incidents assigned to that user.

Ø Create a Script Include that:
Ø Takes a user ID as input.
Ø Uses GlideRecord to query the incident table for active incidents assigned to that user.
Ø Returns the result as a JSON object or array of incidents.


 

and i  have written this code via Background script and script include 

 

SCRIPT INCLUDE : 

 
var Active_incident_fetch = Class.create();
Active_incident_fetch.prototype = {
    initialize: function() {},

    active_rec_fetch: function(userId) {
        if (!userId) {
            gs.addErrorMessage('User_id is required');
            return [];  
        }

        var array_incident = [];
        var incGr = new GlideRecord('incident');
       
        
        incGr.addQuery('assigned_to', userId);
       
      
        incGr.addQuery('state', 'IN_PROGRESS'); 
       
        incGr.query();

 
        gs.info('Found ' + incGr.getRowCount() + ' active incidents for user ' + userId);

 
        if (incGr.getRowCount() === 0) {
            gs.info('No active incidents found for user ' + userId);
            return [];
        }

 
        while (incGr.next()) {
            array_incident.push({
                sys_id: incGr.getValue('sys_id'),
                number: incGr.getValue('number'),
                short_description: incGr.getValue('short_description'),
                priority: incGr.getValue('priority'),
                state: incGr.getValue('state'),
                assigned_to: incGr.getDisplayValue('assigned_to'),
            });
        }

       
        return array_incident;
    },

    type: 'Active_incident_fetch'
};
 
 
BACKGROUND SCRIPT :
 
var activeIncidentFetcher = new Active_incident_fetch();

// Example user ID (replace this with an actual sys_id of the user you want to test)
var userId = '9c573169c611228700193229fff72400';  // Replace with an actual User sys_id

// Log the userId to ensure it's correct
gs.info('Fetching active incidents for user: ' + userId);

// Call the activeRecFetch method from the Script Include and pass the user ID
var incidents = activeIncidentFetcher.active_rec_fetch(userId);
 
if (incidents && incidents.length > 0) {
    gs.info('Active incidents for user (' + userId + '): ' + JSON.stringify(incidents));
} else {
    gs.info('No active incidents found for user (' + userId + ')');
}
2 ACCEPTED SOLUTIONS

Viraj Hudlikar
Giga Sage

Hello @purnendutiw 

Not sure what issue you are facing but few suggestions over code like instead of query with state did with active filter. Also, when printing JSON object added indentation.

 

Your Script Include will be as below:

var Active_incident_fetch = Class.create();
Active_incident_fetch.prototype = {
    initialize: function() {},

    activeRecFetch: function(userId) {
        if (!userId) {
            gs.addErrorMessage('User ID is required');
            return [];
        }

        var arrayIncident = [];
        var incGr = new GlideRecord('incident');
        incGr.addQuery('assigned_to', userId);
        incGr.addQuery('active', true); // Query for active incidents
        incGr.query();

        gs.info('Found ' + incGr.getRowCount() + ' active incidents for user ' + userId);

        while (incGr.next()) {
            arrayIncident.push({
                sys_id: incGr.getValue('sys_id'),
                number: incGr.getValue('number'),
                short_description: incGr.getValue('short_description'),
                priority: incGr.getValue('priority'),
                state: incGr.getValue('state'),
                assigned_to: incGr.getDisplayValue('assigned_to'),
            });
        }
        return arrayIncident;
    },
    type: 'Active_incident_fetch'
};

 

and call from background script will be 

var activeIncidentFetcher = new Active_incident_fetch();

// Example user ID (replace this with an actual sys_id of the user you want to test)
var userId = '5137153cc611227c000bbd1bd8cd2007';  // Replace with an actual User sys_id

// Log the userId to ensure it's correct
gs.info('Fetching active incidents for user: ' + userId);

// Call the activeRecFetch method from the Script Include and pass the user ID
var incidents = activeIncidentFetcher.activeRecFetch(userId);

if (incidents && incidents.length > 0) {
    gs.info('Active incidents for user (' + userId + '): ' + JSON.stringify(incidents, null, 2)); // JSON.stringify(incidents, null, 2) will convert the incidents array into a JSON string with an indentation of 2 spaces, making it more readable in the logs.
} else {
    gs.info('No active incidents found for user (' + userId + ')');
}

and output will be as below:

*** Script: Fetching active incidents for user: 5137153cc611227c000bbd1bd8cd2007
*** Script: Found 2 active incidents for user 5137153cc611227c000bbd1bd8cd2007
*** Script: Active incidents for user (5137153cc611227c000bbd1bd8cd2007): [
  {
    "sys_id": "47064b68a9fe19810186793eefffc9b7",
    "number": "INC0000031",
    "short_description": "Need help with Remedy. Can we configure UI?",
    "priority": "1",
    "state": "2",
    "assigned_to": "David Loo"
  },
  {
    "sys_id": "8d6353eac0a8016400d8a125ca14fc1f",
    "number": "INC0000007",
    "short_description": "Need access to sales DB for the West",
    "priority": "1",
    "state": "3",
    "assigned_to": "David Loo"
  }
]

 

If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.

View solution in original post

Juhi Poddar
Kilo Patron

Hello @purnendutiw 

For practice, your code looks good to me! Here’s some feedback I’d like to share:

  • Proper Utilization of Logs: You’ve effectively used gs.info to debug the script, which is a great practice for troubleshooting.
  • Correct Understanding of Methods: Your use of getValue() and getDisplayValue() demonstrates a solid understanding of these methods and their purpose.
  • Query Improvement: In the Script Include, the query:

 

incGr.addQuery('state', 'IN_PROGRESS');​

can be replaced with:

incidentGr.addQuery('state', 'IN', '1,2'); // 1 = New, 2 = In Progress (default states in ServiceNow)​

 

Since 'IN_PROGRESS' isn’t a default state value, it might not exist in your instance, so adjusting it to match default state values is more reliable.

Hope this helps!

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps future readers to locate the solution easily and supports the community!"

 

Thank You
Juhi Poddar

View solution in original post

3 REPLIES 3

Viraj Hudlikar
Giga Sage

Hello @purnendutiw 

Not sure what issue you are facing but few suggestions over code like instead of query with state did with active filter. Also, when printing JSON object added indentation.

 

Your Script Include will be as below:

var Active_incident_fetch = Class.create();
Active_incident_fetch.prototype = {
    initialize: function() {},

    activeRecFetch: function(userId) {
        if (!userId) {
            gs.addErrorMessage('User ID is required');
            return [];
        }

        var arrayIncident = [];
        var incGr = new GlideRecord('incident');
        incGr.addQuery('assigned_to', userId);
        incGr.addQuery('active', true); // Query for active incidents
        incGr.query();

        gs.info('Found ' + incGr.getRowCount() + ' active incidents for user ' + userId);

        while (incGr.next()) {
            arrayIncident.push({
                sys_id: incGr.getValue('sys_id'),
                number: incGr.getValue('number'),
                short_description: incGr.getValue('short_description'),
                priority: incGr.getValue('priority'),
                state: incGr.getValue('state'),
                assigned_to: incGr.getDisplayValue('assigned_to'),
            });
        }
        return arrayIncident;
    },
    type: 'Active_incident_fetch'
};

 

and call from background script will be 

var activeIncidentFetcher = new Active_incident_fetch();

// Example user ID (replace this with an actual sys_id of the user you want to test)
var userId = '5137153cc611227c000bbd1bd8cd2007';  // Replace with an actual User sys_id

// Log the userId to ensure it's correct
gs.info('Fetching active incidents for user: ' + userId);

// Call the activeRecFetch method from the Script Include and pass the user ID
var incidents = activeIncidentFetcher.activeRecFetch(userId);

if (incidents && incidents.length > 0) {
    gs.info('Active incidents for user (' + userId + '): ' + JSON.stringify(incidents, null, 2)); // JSON.stringify(incidents, null, 2) will convert the incidents array into a JSON string with an indentation of 2 spaces, making it more readable in the logs.
} else {
    gs.info('No active incidents found for user (' + userId + ')');
}

and output will be as below:

*** Script: Fetching active incidents for user: 5137153cc611227c000bbd1bd8cd2007
*** Script: Found 2 active incidents for user 5137153cc611227c000bbd1bd8cd2007
*** Script: Active incidents for user (5137153cc611227c000bbd1bd8cd2007): [
  {
    "sys_id": "47064b68a9fe19810186793eefffc9b7",
    "number": "INC0000031",
    "short_description": "Need help with Remedy. Can we configure UI?",
    "priority": "1",
    "state": "2",
    "assigned_to": "David Loo"
  },
  {
    "sys_id": "8d6353eac0a8016400d8a125ca14fc1f",
    "number": "INC0000007",
    "short_description": "Need access to sales DB for the West",
    "priority": "1",
    "state": "3",
    "assigned_to": "David Loo"
  }
]

 

If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.

Juhi Poddar
Kilo Patron

Hello @purnendutiw 

For practice, your code looks good to me! Here’s some feedback I’d like to share:

  • Proper Utilization of Logs: You’ve effectively used gs.info to debug the script, which is a great practice for troubleshooting.
  • Correct Understanding of Methods: Your use of getValue() and getDisplayValue() demonstrates a solid understanding of these methods and their purpose.
  • Query Improvement: In the Script Include, the query:

 

incGr.addQuery('state', 'IN_PROGRESS');​

can be replaced with:

incidentGr.addQuery('state', 'IN', '1,2'); // 1 = New, 2 = In Progress (default states in ServiceNow)​

 

Since 'IN_PROGRESS' isn’t a default state value, it might not exist in your instance, so adjusting it to match default state values is more reliable.

Hope this helps!

 

"If you found my answer helpful, please like and mark it as an "accepted solution". It helps future readers to locate the solution easily and supports the community!"

 

Thank You
Juhi Poddar

Hello @purnendutiw 

Thank You for marking my response as helpful.

I hope I have also answered your query and pointed out the error and provided solution for the same.

Could you also please mark my response as an accepted solution.

 

Thank You

Juhi Poddar