Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to group the incident records based on manager of assigned_to?

ArpitaVK
Tera Expert

Hello

In a scheduled job script, I want to group the incident records based on the manager of assigned_to user. Then, I want to fire an event to send notifications to each of those managers. How to group them in script?

I used GlideAggregate() which gives me count of those records instead of grouping them based on manager.

2 REPLIES 2

Maddysunil
Kilo Sage

@ArpitaVK 

you can use GlideAggregate along with the GROUP BY clause.

 

var ga = new GlideAggregate('incident');
ga.addNotNullQuery('assigned_to');

// Add a condition to filter incidents that are not closed
ga.addQuery('state', '!=', 6); // 6 represents the 'Closed' state, adjust this value according to your instance

// Add a group-by clause to group incidents by the manager of assigned_to user
ga.addAggregate('GROUPBY', 'assigned_to.manager');

// Execute the query
ga.query();

// Process each group of incidents
while (ga.next()) {
    // Get the manager for the group
    var manager = ga.getElement('assigned_to.manager');

    // Query all incidents belonging to this manager's team
    var managerIncidents = new GlideRecord('incident');
    managerIncidents.addQuery('assigned_to.manager', manager);
    managerIncidents.addQuery('state', '!=', 6); // Exclude closed incidents
    managerIncidents.query();

    // Process each incident belonging to this manager's team
    while (managerIncidents.next()) {
        // Send notification or trigger an event for each incident
        // Here you can implement the logic to send notifications or trigger an event
        // Example: gs.eventQueue('incident_notification', managerIncidents, managerIncidents.assigned_to.manager.getDisplayValue());
    }
}

 

Please Mark Correct if this solves your query and also mark 👍Helpful if you find my response worthy based on the impact.

 

Thanks

Vishwa Pandya19
Mega Sage

Hi Arpita,

 

You can use the below script to achieve the requirement.

var ga = new GlideAggregate('incident');
ga.addEncodedQuery('active=true^assigned_to!=NULL');
ga.groupBy('assigned_to');
ga.query();

var obj = [];
while(ga.next()){
	obj.push(ga.assigned_to.manager.getDisplayValue());
}


var obj2 = [];
for(var i = 0; i <= obj.length; i++){
	var gr1 = new GlideRecord('sys_user');
	gr1.addEncodedQuery('name='+obj[i]);
	gr1.query();

	while(gr1.next()){
		obj2.push(gr1.email.toString());
	}

}

//After getting email id's in an array (obj2) you can now trigger the event for the notification
//gs.eventQueue();

 

 

If my answer helped you in any way please mark it as correct or helpful.