Usecase: Calculate the average time taken to close incidents for a specific user.
Description: Build a Script Include that calculates the average time taken to close incidents for a specific user based on their resolved incidents.
script include
Working Code Answered question January 3, 2024
- Go to "System Definition" > "Script Includes" in ServiceNow.
- Click on "New" to create a new Script Include.
- Copy and paste the above code into the Script field.
- Save the Script Include.
// Name: UserAverageResolutionTimeCalculator // Table: Incident var UserAverageResolutionTimeCalculator = Class.create(); UserAverageResolutionTimeCalculator.prototype = { initialize: function() { }, // Function to calculate average resolution time for a specific user calculateAverageResolutionTimeForUser: function(userId) { var gr = new GlideRecord('incident'); gr.addQuery('closed_by', userId); gr.addNotNullQuery('resolved_at'); gr.query(); var totalResolutionTime = 0; var incidentCount = 0; while (gr.next()) { var resolvedAt = new GlideDateTime(gr.resolved_at); var closedAt = new GlideDateTime(gr.closed_at); var resolutionTime = new GlideDuration(resolvedAt.getNumericValue() - closedAt.getNumericValue()); totalResolutionTime += resolutionTime.getNumericValue(); incidentCount++; } // Avoid division by zero if (incidentCount > 0) { var averageResolutionTime = totalResolutionTime / incidentCount; return new GlideDuration(averageResolutionTime).getDisplayValue(); } else { return "No resolved incidents closed by the specified user."; } }, type: 'UserAverageResolutionTimeCalculator' };
you can use this Script Include in other scripts, such as Business Rules, UI Actions, or Scheduled Jobs, to calculate the average time taken to close incidents for a specific user.
Example usage in a Business Rule:
// Business Rule to log average resolution time for a specific user var userId = gs.getUserID(); // Set the desired user ID var calculator = new UserAverageResolutionTimeCalculator(); var averageResolutionTime = calculator.calculateAverageResolutionTimeForUser(userId); gs.info("Average Resolution Time for User " + userId + ": " + averageResolutionTime);
script include
Working Code Answered question January 3, 2024