Yes, that’s a good practice! If you put the condition in the Business Rule’s When to run (the Condition field), then you don't need to repeat it in the script.
Here’s how you can configure the Business Rule:
Condition (in Business Rule form)
current.assignment_group.changes()
This means: the rule runs only if the assignment group field is changed.
Then the Business Rule script can be simplified to:
(function executeRule(current, previous /*null when async*/) {
if (!current.assignment_group)
return; // no assignment group, do nothing
var groupID = current.assignment_group.toString();
var grMember = new GlideRecord('sys_user_grmember');
grMember.addQuery('group', groupID);
grMember.query();
var userLoadMap = {}; // map user sys_id => count of incidents assigned
// Initialize each group member with 0
while (grMember.next()) {
var userId = grMember.user.toString();
userLoadMap[userId] = 0;
}
if (Object.keys(userLoadMap).length === 0) {
// no users in group, clear assigned_to
current.assigned_to = '';
return;
}
// Aggregate incidents assigned to these users that are active
var grIncident = new GlideAggregate('incident');
grIncident.addAggregate('COUNT');
grIncident.addQuery('assigned_to', 'IN', Object.keys(userLoadMap).join(','));
grIncident.addQuery('active', true);
grIncident.groupBy('assigned_to');
grIncident.query();
while (grIncident.next()) {
var assignedTo = grIncident.getValue('assigned_to');
var count = parseInt(grIncident.getAggregate('COUNT'), 10);
userLoadMap[assignedTo] = count;
}
// Find user with minimum assigned incidents
var minAssignedUser = null;
var minCount = Number.MAX_SAFE_INTEGER;
for (var userSysId in userLoadMap) {
if (userLoadMap.hasOwnProperty(userSysId)) {
if (userLoadMap[userSysId] < minCount) {
minCount = userLoadMap[userSysId];
minAssignedUser = userSysId;
}
}
}
if (minAssignedUser) {
current.assigned_to = minAssignedUser;
} else {
current.assigned_to = '';
}
})(current, previous);
Summary:
- Put the condition
current.assignment_group.changes() in the Business Rule condition field.
- The script assumes the assignment group changed when it runs, so no need to check again.
- The script finds the least loaded user in that group and sets
assigned_to.
Let me know if you want me to help with the full Business Rule config or test cases!